您的位置:首页 > 其它

WPF中多幅图片的显示

2013-03-19 15:23 169 查看
只是想在WPF下编写一个简单的框架,能够显示文件夹中的图片。
由于想要显示不同类型的图片,就创建了一个TabControl,再在每一个TabItem里面添加了一个Image控件来显示图片。还加入了一些按钮用来控制上一张或者下一张图片的显示。

<Grid>
<TabControl Height="500" HorizontalAlignment="Left" Margin="460,12,0,0" Name="tabControl" VerticalAlignment="Top" Width="420">
<TabItem Header="Glass" Name="tabItem1">
<Grid>
<Image Height="460" Margin="0,0,0,0" Name="imageGlass" Stretch="Fill" VerticalAlignment="Top" Width="400" />
</Grid>
</TabItem>
<TabItem Header="Watch" Name="tabItem2" >
<Grid>
<Image Height="460" Margin="0,0,0,0" Name="imageWatch" Stretch="Fill" VerticalAlignment="Top" Width="400"  />
</Grid>
</TabItem>
</TabControl>
<Image Height="500" HorizontalAlignment="Left" Margin="12,12,0,0" Name="imageBody" Stretch="Fill" VerticalAlignment="Top" Width="420"  />
<Button Content="确    定" Height="23" HorizontalAlignment="Left" Margin="320,525,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<Button Content="上一张" Height="23" HorizontalAlignment="Left" Margin="540,525,0,0" Name="bottonPrior" VerticalAlignment="Top" Width="75" Click="buttonPrior_Click"  />
<Button Content="下一张" Height="23" HorizontalAlignment="Left" Margin="710,525,0,0" Name="bottonNext" VerticalAlignment="Top" Width="75" Click="buttonNext_Click"  />
</Grid>

因为需要显示文件夹下的图片,就要得到文件夹内图片的路径,我将这些图片分类后放在了不同的文件夹下,并定义了路径数组:

string[] pathGlass = System.IO.Directory.GetFiles("E:\\C#\\201303\\glass");
string[] pathWatch = System.IO.Directory.GetFiles("E:\\C#\\201303\\watch");
int numGlass = 0;
int numWatch = 0;


pathGlass数组内存放了glass文件夹下的所有图片的路径信息,并为该数组定义了游标numGlass,为遍历时确定图片索引。

在上面XAML框架设计中,定义的Image控件,通过调用Source可以显示图片,所以需要将图片运用路径信息得到该图片的位图信息传给相应的Source。于是就定义了如下的方法:

private BitmapImage colorBitmap(string path)
{
BitmapImage bitmapImage;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = System.IO.File.OpenRead(path);
bitmapImage.EndInit();
return bitmapImage;
}

这样一来只需调用该方法就能将图片传递给界面显示:

public MainWindow()
{
InitializeComponent();
if (pathGlass.Length>=1)
{
this.imageGlass.Source = colorBitmap(pathGlass[0]);
}
if (pathWatch.Length >= 1)
{
this.imageWatch.Source = colorBitmap(pathWatch[0]);
}
}
接下来就是点击按钮事件了,因为定义了TabControl控件,当选中某一个TabItem后,相应的按钮事件就要执行该TabItem下的内容了。就拿点击“上一张”按钮而言:

private void buttonPrior_Click(object sender, RoutedEventArgs e)
{
if (this.tabItem1.IsSelected)
{
if (numGlass == 0)
{
numGlass = pathGlass.Length - 1;
}
else numGlass--;
this.imageGlass.Source = colorBitmap(pathGlass[numGlass]);
}
if (this.tabItem2.IsSelected)
{
if (numWatch == 0)
{
numWatch = pathWatch.Length - 1;
}
else numWatch--;
this.imageWatch.Source = colorBitmap(pathWatch[numWatch]);
}
}

最终效果图为:



刚开始学C#没多久,左边的空白部分是打算显示Kinect摄像结果的。这也是第一份CSDN的博文,以后打算好好学习,经常光顾CSDN,想要坚持把学到的知识记录下来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息