WPF矩形填充图像画笔ImageSource

时间:2018-04-01 12:20:01

标签: c# wpf image

我正在尝试用图像填充矩形,图像存储在项目根目录中的文件夹中。所以BrushesAndPens / Images / oog.png

现在,当我通过Xaml将图像添加到矩形时,这可以正常工作,但是当我动态地执行它时,它会找到路径,但之后会抛出异常错误。 代码和错误如下。我非常确定我的代码是正确的,并且图像位于正确的文件夹中。

代码:

 ImageBrush imgBrush = new ImageBrush();
 imgBrush.ImageSource = new BitmapImage(new Uri(@"Images/oog.png", UriKind.Relative));
 Rect6.Fill = imgBrush;

例外:

ExceptionImageLINK

1 个答案:

答案 0 :(得分:0)

如果图像文件是程序集资源,即Visual Studio项目中文件的Build Action设置为Resource,则必须由Resource File Pack URI加载。在XAML中,URI前缀是自动添加的,您必须在后面的代码中明确地写入它:

imgBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Images/oog.png"));
相关问题