我怎样将PictureBox的图像设置为我的资源文件中的图像?
(我尝试过以下方法但没有成功:pictuerbox.Image = "img_location";
)
我怎样将PictureBox的图像设置为我的资源文件中的图像?
(我尝试过以下方法但没有成功:pictuerbox.Image = "img_location";
)
如果您是使用 Visual Studio UI 加载资源的话,那么您应该可以这样做:
picturebox.Image = project.Properties.Resources.imgfromresource
Ken有正确的解决方案,但你不想添加picturebox.Image.Load()成员方法。
如果你使用Load()且ImageLocation未设置,它将失败并抛出“必须设置图像位置”异常。如果您使用picturebox.Refresh()成员方法,则可以避免异常。
下面是完成的代码:
public void showAnimatedPictureBox(PictureBox thePicture)
{
thePicture.Image = Properties.Resources.hamster;
thePicture.Refresh();
thePicture.Visible = true;
}
它被调用为: showAnimatedPictureBox( myPictureBox );
我的XAML如下:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
Title="myApp" Height="679.079" Width="986">
<StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
<wfi:WindowsFormsHost>
<winForms:PictureBox x:Name="myPictureBox">
</winForms:PictureBox>
</wfi:WindowsFormsHost>
<Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
</StackPanel>
</Window>
我知道这是一篇旧帖子,但从资源直接加载图像在微软网站上非常不清楚,这是我想到的(部分)解决方案。希望能对某人有所帮助!
好的... 首先,你需要将图片导入到你的项目中
1). 在表单设计中选择图片框
2). 打开PictureBox任务(它是图片框边缘上指向右边的小箭头)
3). 点击“选择图片...”
4). 选择第二个选项“项目资源文件:”(此选项将创建一个名为“Resources”的文件夹,你可以通过Properties.Resources访问该文件夹)
5). 点击导入并从你的计算机中选择图片(现在,一个与图片同名的副本将被发送到在第4步创建的Resources文件夹中)
6). 点击确定
现在图片已经在你的项目中,你可以使用Properties命令来使用它。当你想要更改图片框中的图片时,只需输入以下代码:
pictureBox1.Image = Properties.Resources.myimage;
myPictureBox.Image = global::mynamespace.Properties.Resources.photo1;
将命名空间替换为您的项目命名空间
您可以使用资源管理器来加载图片。
请参见以下链接: http://www.java2s.com/Code/CSharp/Development-Class/Saveandloadimagefromresourcefile.htm
您必须将资源文件的完整路径指定为应用程序资源中的'image'名称,如下面的示例所示。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = My.Resources.Chrysanthemum
End Sub
pictureBox.Load();
才能显示图片,仅从资源中分配它是不起作用的。 - Habib