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

1.8k Views Asked by At

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?

2

There are 2 best solutions below

6
Clemens On BEST ANSWER

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"));
0
rmojab63 On

This works:

var d = new System.Windows.Shapes.Ellipse();
ImageBrush ib = new ImageBrush();
ib.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("images/error.png", UriKind.Relative));
d.Fill = ib;

this.Content = d; // assuming the parent is a Window

Note two things:

  1. There is an image in images directory named error.png
  2. Click on the image file and from the properties window, set Build Action to Content and also set Copy to Output Directory to Copy Always.