如何在 C# 代码中创建 ImageBrush
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13535587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Create ImageBrush in C# code
提问by dongx
In XAML:
在 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>
XAML works fine, but how to create the above ImageBrushin C# code:
XAML 工作正常,但如何在 C# 代码中创建上述ImageBrush:
C# should be like this:
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")));
采纳答案by Adi Lester
I'm guessing the problem is with locating the image and that the exception you're getting is because you don't provide the UriKindparameter. Try giving UriKind.Relativeas a parameter to the Uri:
我猜问题在于定位图像,而您得到的异常是因为您没有提供UriKind参数。尝试将其UriKind.Relative作为参数提供给Uri:
rectangle.Fill = new ImageBrush(new BitmapImage(
new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg", UriKind.Relative)));
回答by SinhaOjas
In c# you can use it like , first thing is remove the fill from XAML then use the same code in c# as you have used it . It must work.
在 c# 中,您可以像这样使用它,首先是从 XAML 中删除填充,然后在 c# 中使用与您使用过的代码相同的代码。它必须工作。
ImageBrush ib = new ImageBrush();
ib.ImageSource = new BitmapImage(new Uri("your path",UriKind.Relative));
rectangle.Fill = ib;
回答by Kibernetik
This code creates ImageBrush using image "Assets/image.png" which is part of the UWP project. Relative paths are unavailable in UWP version of ImageBrush.
此代码使用作为 UWP 项目一部分的图像“Assets/image.png”创建 ImageBrush。相对路径在 UWP 版本的 ImageBrush 中不可用。
var imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/image.png"));

