Click here to Skip to main content
11,806,931 members (62,589 online)

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))
       Dim bmp As New RenderTargetBitmap(Me.Height, Me.Width, 96, 96, PixelFormats.Pbgra32)
       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: VB, VB.NET, .NET (.NET4.5), WPF


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.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

Advertise | Privacy | Mobile
Web01 | 2.8.151002.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100