Search code examples
c#wpfpngjpegimagebrush

Dynamically Fill Ellipse with png/jpg image? ImageBrush not helpful, URI not working


Okay, So I have read some of the questions here, all of them with same or similar answers, I'm trying to insert an image to an ellipse from code.

ImageBrush ib = new ImageBrush();
        ib.ImageSource = new BitmapImage(new Uri("Art/image.png", UriKind.Relative));
        Sun.Fill = ib;

With this code nothing happens, I get black screen and lose some of the objects also. I have altered the code, removing UriKind, changing it to absolute, to RelativeOrAbsolute, I have tried with @"Art\image.png". All adds up to the same end. But when I Do it In XAML, it works. Is there a solution to this problem?


Solution

  • Make the image file an assembly resource. This is more practical than having separate content files.

    The file image.png should be located in a folder called Art in your Visual Studio Project, and it's Build Action (in the file's Properties) should be set to Resource.

    Then you would use a Resource File Pack URI to access the file:

    ib.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Art/image.png"));