使用用户选择的图像作为画布背景
本文关键字:布背景 背景 用户 选择 图像 | 更新日期: 2023-09-27 18:30:57
删除了我的旧问题,以便我可以提出更具体的问题。我使用 http://www.c-sharpcorner.com/uploadfile/mahesh/image-viewer-in-wpf/的代码作为基础。允许用户浏览要打开和显示的图像文件。我想显示一个图像,然后让用户在上面做标记。我决定为此使用画布。现在,我不知道如何让用户选择的图像作为背景。我收到一个错误,说"System.Windows.Shapes.Path不包含'背景'的定义,并且找不到接受类型为'System.Windows.Shapes.Path'的第一个参数的扩展方法'背景'..."从说"画布1.背景=画笔;"。我已经查找了设置画布背景的方法,其中一些仅涉及使用 xaml 代码,但随后出现其他错误。
XAML:
<Window x:Class="CanvasStuff.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="409" Width="574">
<Grid >
<Label Content="Image" Height="32" HorizontalAlignment="Left" Margin="11,10,0,0"
Name="selectedFileName" VerticalAlignment="Top" Width="393"
Background="LightGray" BorderBrush="Gray" BorderThickness="1"/>
<Button Content="Browse File" Height="34" HorizontalAlignment="Left" Margin="410,8,0,0"
Name="BrowseButton" VerticalAlignment="Top" Width="119"
Foreground="Maroon" FontSize="16" FontFamily="Georgia" Click="BrowseButton_Click" />
<Canvas>
<Path Canvas.Left="61" Canvas.Top="28" Width="133" Height="98" Fill="Blue"
Stretch="Fill" Data="M61,125 L193,28" Name="canvas1"/>
</Canvas>
</Grid>
</Window>
代码隐藏:
namespace CanvasStuff
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:''";
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));
canvas1.Background = brush; #error here
BitmapImage bitmap = new BitmapImage();
}
}
}
}
"canvas1"元素是一个路径,因此它具有填充属性而不是背景属性,因此您可以替换 canvas1。背景与画布1。填补。但这不会给你一个背景,因为该路径只有很小的尺寸。你真的希望你的窗口有一个背景,你可以使用一个包含的边框来完成。
<Window x:Class="CanvasStuff.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="409" Width="574">
<Border x:Name="bgBorder" BorderThickness="0">
<!-- insert your current content here -->
</Border>
</Window>
然后只需更换
canvas1.Background = brush;
跟
bgBorder.Background = brush;
多亏了
博尼乔和国王国王,才想通了。我的主要问题是我忘了取出我在前面的例子中使用的路径(不想在那里)。所以我的画布 .xaml 代码现在看起来像这样:
<Canvas Margin="0,48,0,0" x:Name="canvas1">
</Canvas>
这解决了我想要做的事情。