以编程方式将图像附加到椭圆

Mic*_*ael 2 c# wpf

当我运行此代码时,在我最大化应用程序之前会出现黑屏?另外,我认为它也不会拾取图像文件。在 Visual Studio 中,我创建了一个新文件夹并将图像添加到该文件夹​​中。

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);
}
Run Code Online (Sandbox Code Playgroud)

Xia*_* Yu 5

您正在使用有什么特别的原因TextureBrush吗?

不太确定,但也许您应该ImageBrush改用。

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