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

时间:2012-03-11 19:13:34

标签: 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);
}

1 个答案:

答案 0 :(得分:3)

您使用TextureBrush是否有任何特殊原因?

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

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