1.概述
最近利用WPF做了一个图片浏览器,能够将文件夹中的所有图片以小图的形式显示,并将选中的图片以512*512大小显示。显示大图当然用的是WPF自带的Image控件,而显示小图则需要将所有的图片放入ListBox控件中,ListBox里的每一个Item为Image控件。为了方便显示多张小图,在ListBox控件外加入了ScrollViewer控件,以便可以拖动显示ListBox中的Item。并实现了对图片的一系列操作,如放大、缩小、恢复1:1的比例、上一张、下一张等功能。效果图如下:
2.XAML设计
2.1 ScrollViewer样式
即为滚动条添加一个动画,只有鼠标移到滚动条或是通过滑轮切换图片,或是连续点击上一张、下一张按钮时,滚动条才会显示,其他状态下隐藏。
2.2 ListBox样式
<Style TargetType="{x:Type ListBox}" x:Key="PhotoListBoxStyle">
<Setter Property="Foreground" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}" >
<WrapPanel Margin="5" IsItemsHost="True" Orientation="Horizontal" ItemHeight="{Binding ElementName=ZoomSlider, Path='Value'}" ItemWidth="{Binding ElementName=ZoomSlider,
Path='Value'}" VerticalAlignment="Top" HorizontalAlignment="Stretch" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ScrollViewer Panel.ZIndex="1" Name="scrolls" Style="{StaticResource for_scrollviewer}" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Visible" Margin="181,561,1107,0" MaxWidth="560"
Height="174" VerticalAlignment="Top" Canvas.Left="463" Canvas.Top="158" Width="516" HorizontalAlignment="Center" HorizontalContentAlignment="Center">
<ListBox IsSynchronizedWithCurrentItem="True" Name="list1" Style="{StaticResource PhotoListBoxStyle}" Margin="5" SelectionMode="Extended" SelectedIndex="-1" Height="150" SelectionChanged="list1_SelectionChanged"
UIElement.MouseWheel="ImageList_MouseWheel">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Blue" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Blue" Opacity=".3"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="White" />
</Style.Resources>
</Style>
</ListBox.Resources>
</ListBox>
</ScrollViewer>
2.3 Button样式
操作按钮放在一个StackPanel中,当鼠标移入的时候按钮的透明度发生变化,以1:1按钮的样式为例 如下:
<Style x:Key = "ImgButton" TargetType = "P{x:Type Button}">
<Setter Property = "Cursor" Value = "Hand"></Setter>
<Setter Property = "Width" Value = "35"></Setter>
<Setter Property = "Height" Value = "30"></Setter>
</Style>
<Style x:Key = "UndoStyle" TargetType = "{x:Type Button}" BasedOn = "{StaticResource ImgButton}">
<Setter Property = "Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border>
<Image Name="img" Source="/DoctorOld;component/Images/undo.png">
</Image>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.7">
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
3.后台代码
3.1 初始化
首先定义一个ArrayList用于存放图片的名称,即 ArrayList myArrayList = new ArrayList();
然后将指定文件夹中的所有图像的名称信息放到myArrayList中
DirectoryInfo Dir = new DirectoryInfo("D:\\myPic);
foreach (FileInfo file in Dir.GetFiles("*.png", System.IO.SearchOption.AllDirectories))
{
str = file.ToString();
myArrayList.Add(str);
}
如果图片的数量大于0,就执行AddImg()函数
if (newArrayList.Count > 0)
{
for (int i = 0; i < newArrayList.Count; i++)
{
AddImg("D:\\myPic + "\\" + newArrayList[i].ToString());
}
}
将图片添加到ListBox中的函数如下:
public void AddImg(string szPath)
{
string[] s = szPath.Split(new char[] { '\\' }); //按照“\\”截取字符串,即为了获取图片的名称
System.Windows.Controls.Image listImage = new System.Windows.Controls.Image(); //创建一个Image控件
Border br = new Border();
BitmapImage bitmapImage = new BitmapImage();
ListBoxItem newListBox = new ListBoxItem(); //创建一个ListBoxItem,作为ListBox的元素
//将指定路径的图片加载到名为listImage的Image控件中,请参考http://blog.csdn.net/wangshubo1989/article/details/46710411
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.UriSource = new Uri(szPath);
bitmapImage.EndInit();
bitmapImage.Freeze();
listImage.Source = bitmapImage;
//设置border的高、宽、圆角
br.Width = 106;
br.Height = 106;
br.CornerRadius = new CornerRadius(10);
Label PicLabel = new Label();//鼠标移到图片上显示图片的名称
listImage.ToolTip = s[2]; //获得图片的名称,例如全路径为 D:\\myPic\\123.png,即将提示的字符串赋值为123.png
//Image添加到Border中
br.Child = listImage;
br.Padding = new System.Windows.Thickness((float)1.1f);
br.Background = System.Windows.Media.Brushes.White;
br.BorderThickness = new System.Windows.Thickness((int)3);
//阴影效果
DropShadowEffect myDropShadowEffect = new DropShadowEffect();
// Set the color of the shadow to Black.
System.Windows.Media.Color myShadowColor = new System.Windows.Media.Color();
myShadowColor.A = 255;
// Note that the alpha value is ignored by Color property.
// The Opacity property is used to control the alpha.
myShadowColor.B = 50;
myShadowColor.G = 50;
myShadowColor.R = 50;
myDropShadowEffect.Color = myShadowColor;
// Set the direction of where the shadow is cast to 320 degrees.
myDropShadowEffect.Direction = 310;
// Set the depth of the shadow being cast.
myDropShadowEffect.ShadowDepth = 20;
// Set the shadow softness to the maximum (range of 0-1).
myDropShadowEffect.BlurRadius = 10;
// Set the shadow opacity to half opaque or in other words - half transparent.
// The range is 0-1.
myDropShadowEffect.Opacity = 0.4;
// Apply the effect to the Button.
newListBox.Effect = myDropShadowEffect;
newListBox.Content = br;
newListBox.Margin = new System.Windows.Thickness((int)10);
newListBox.DataContext = szPath;
list1.Items.Add(newListBox); //list1为界面上ListBox控件的名称
list1.SelectedIndex = list1.Items.Count - 1;
scrolls.ScrollToRightEnd(); //使得滚动条 滚到最后, scrolls为ScrollViewer控件的名称
}
3.2 放大
首先写一个图片大小变化的函数,参数为布尔型,用于判断是放大还是缩小,其中image1为显示大图的Image控件的名称
private void ChangImgSize(bool big)
{
Matrix m = image1.RenderTransform.Value;
System.Windows.Point p = new System.Windows.Point((image1.ActualWidth) / 2, (image1.ActualHeight) / 2);
if (big)
{
m.ScaleAtPrepend(1.1, 1.1, p.X, p.Y);
}
else
{
m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, p.X, p.Y);
}
image1.RenderTransform = new MatrixTransform(m);
}
所以对于点击放大按钮函数如下:
private void btnBig_Click(object sender, RoutedEventArgs e)
{
ChangImgSize(true);
}
同时,可以通过滚动鼠标滑轮来进行放大缩小,通过判断e.Delta的正负来判读是向上还是向下滚动鼠标换轮
private void Image_MouseWheel(object sender, RoutedEventArgs e)
{
ChangImgSize(e.Delta>0);
}
3.3 缩小
原理如上,顾点击缩小按钮的函数如下
private void btnSmall_Click(object sender, RoutedEventArgs e)
{
ChangImgSize(false);
}
同时,可以通过滚动鼠标滑轮来进行缩小
3.4 恢复1:1
点击1:1按钮 即恢复512*512的大小的图像
private void btnUndo_Click(object sender, RoutedEventArgs e)//恢复图像512*512大小
{
image1.RenderTransform = new MatrixTransform(new Matrix(1, 0, 0, 1, 0, 0));
}
3.5 下一张
private void nextStyle_Click(object sender, RoutedEventArgs e)//点击下一张按钮
{
m_nImgCount = list1.SelectedIndex + 1; //m_nImgCount 为静态全局变量,用于存储当前小图的数量
if (m_nImgCount < m_nPicNum)
{
list1.SelectedIndex++;
BitmapImage bitmapImage1 = new BitmapImage();
bitmapImage1.BeginInit();
bitmapImage1.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage1.UriSource = new Uri("D:\\myPic" + newArrayList[list1.SelectedIndex].ToString());
bitmapImage1.EndInit();
bitmapImage1.Freeze();
image1.Source = bitmapImage1;
scrolls.ScrollToHorizontalOffset(list1.SelectedIndex * 130);
}
else
{
MessageBox.Show("No Image");
}
}
3.6 上一张
原理和下一张操作相同,不在赘述。
3.7 删除
请参照文章 http://blog.csdn.net/wangshubo1989/article/details/46710411
4.总结
一个图片查看器就此呈现在你的眼前,可以进一步的丰富界面效果。如果有疑问、错误、代码优化、需要更多源码等问题,欢迎留言。
邮箱:wangshubo1989@126.com