Click here to Skip to main content
15,891,431 members

Using RenderTargetBitmap and DrawingVisual

Kenneth Haugland asked:

Open original thread
Here goes:

I want to set a background image on a Canvas, using ImageBrush. The trouble starts when I want to resize the Canvas and leave the background picture intact. Meaning it will stay the same size in the topleft corner.

This is what I tried:
Private Function GenerateImageBrush(ByVal image As ImageSource, Optional ByVal SizeNew As Boolean = False) As ImageBrush
       Dim result As New ImageBrush

       Dim drawingVisual As New DrawingVisual()
       Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()
       drawingContext.DrawRectangle(Brushes.White, New Pen(Brushes.Black, 1), New Rect(New Size(Me.Height, Me.Width)))
       drawingContext.DrawImage(image, New Rect(0, 0, imgWidth, imgHeight))
       drawingContext.Close()

       Dim bmp As New RenderTargetBitmap(Me.Height, Me.Width, 96, 96, PixelFormats.Pbgra32)
       bmp.Render(drawingVisual)

       result.ImageSource = bmp
       Return result
   End Function

   Dim imgWidth, imgHeight as Double

   Public Sub AddPicture(ByVal pic As String)
       Dim imgConv = New ImageSourceConverter()
       Dim imageSource As ImageSource
       imageSource = DirectCast(imgConv.ConvertFromString(pic), ImageSource)

       imgWidth = imageSource.Width
       imgHeight = imageSource.Height

       Me.Width = imageSource.Width
       Me.Height = imageSource.Height

       Me.Background = GenerateImageBrush(imageSource)
   End Sub


The idea is to return an Image that has preserved its original size, and filled the rest of the space with white color.

But When I try to resize the canvas, the picture starts to deform. It seems to want to preserve the original ratio Length/Width and adusts the image accordingly. But I cant seem to find out how to do this, does anybody know how to get this to work?
Tags: Visual Basic, .NET (.NET4.5), WPF

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900