在XAML中:
<Rectangle Stroke="Aqua" Opacity="0.7" StrokeThickness="10" Canvas.Left="24" Canvas.Top="22" Height="86" Width="102">
<Rectangle.Fill>
<ImageBrush ImageSource="C:\Users\xiaorui.dong\Pictures\profile.jpeg"></ImageBrush>
</Rectangle.Fill>
</Rectangle>
Run Code Online (Sandbox Code Playgroud)
XAML工作正常,但如何在C#代码中创建上面的ImageBrush:
C#应该是这样的:
Rectangle rectangle = new Rectangle();
rectangle.StrokeThickness = 10;
rectangle.Height = 200;
rectangle.Width = 100;
rectangle.SetValue(Canvas.LeftProperty, 100d);
rectangle.SetValue(Canvas.TopProperty, 100d);
rectangle.Fill = new ImageBrush(new BitmapImage(new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg")));
Run Code Online (Sandbox Code Playgroud)
Adi*_*ter 13
I'm guessing the problem is with locating the image and that the exception you're getting is because you don't provide the UriKind parameter. Try giving UriKind.Relative as a parameter to the Uri:
rectangle.Fill = new ImageBrush(new BitmapImage(
new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg", UriKind.Relative)));
Run Code Online (Sandbox Code Playgroud)
小智 8
在c#中你可以使用它,首先是从XAML中删除填充然后在c#中使用相同的代码,就像你使用它一样.它必须工作.
ImageBrush ib = new ImageBrush();
ib.ImageSource = new BitmapImage(new Uri("your path",UriKind.Relative));
rectangle.Fill = ib;
Run Code Online (Sandbox Code Playgroud)