Michael
Michael

Reputation: 2128

Attaching an image to an Ellipse programmatically

When I run this code, I get a black screen until i maximise the application? Also, I don't think its picking up the image file neither. Within Visual Studio, I made a new folder and added the image to this folder.

public MainWindow()
{
    InitializeComponent();

    Canvas canvas = new Canvas();
    canvas.Width = 300;
    canvas.Height = 300;
    canvas1.Children.Add(canvas);

    Ellipse hand = new Ellipse();
    hand.Height = 30;
    hand.Width = 30;
    /*
    BrushConverter bc = new BrushConverter();
    Brush brush = (Brush)bc.ConvertFrom("Red");
    hand.Fill = new SolidColorBrush(Colors.Red);
    */
    ImageBrush myBrush = new ImageBrush();
    myBrush.ImageSource =
        new BitmapImage(new Uri(@"Images/Hand.png", UriKind.Relative));
    hand.Fill = myBrush;

    Canvas.SetLeft(hand, 100);
    Canvas.SetTop(hand, 100);
    canvas.Children.Add(hand);
}

Upvotes: 2

Views: 5784

Answers (1)

XiaoChuan Yu
XiaoChuan Yu

Reputation: 4011

Is there any particular reason that you are using TextureBrush?

Not really sure but maybe you should be using ImageBrush instead.

ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = 
    new BitmapImage(new Uri("pack://application:,,,/Images/image.jpg"));
myEllipse.Fill = myBrush;

Upvotes: 4

Related Questions