这几天一直在研究如何用wpf制作类似于windows自带的图片查看器,网上也有些类似的,但功能单一,和windows自带的图片查看器有很大区别,于是自己做了个图片查看器,功能大部分健全,首先是绘制图片展示界面,如图

,下面分别是放大、全屏、左转、右转、恢复原图、下一张以及删除按钮,上面是一个打开文件按钮。首先是绘制界面,这里不多说了,会wpf的,这个界面其实是很简单的。界面绘制好后,我们需要建立一个获取选中图片的文件目录类,如下:

public class ImageFile
    {
        private string ImageFolderPath;
        public ImageFile(string ImageFolderPath)
        {
            this.ImageFolderPath = ImageFolderPath;
        }
         /// <summary>         
         /// 获取选中文件夹下的所有图片
        /// </summary>
        public List<string> GetImgInfo
        {
            get
           {
                 List<string> imgs = new List<string>();
                 string[] ft = { ".GIF", ".PNG", ".BMP", ".JPG", ".JPEG" };//图片格式
                 DirectoryInfo dt = new DirectoryInfo(ImageFolderPath);
                 FileInfo[] fis = dt.GetFiles();
                if (fis == null)
                {
                    return null;
                }
                else
                {
                    foreach (FileInfo f in fis)
                    {
                        if (ft.Contains<string>(f.Extension.ToUpper()))
                        {
                            imgs.Add(f.FullName);
                        }
                    }
                }
                return imgs;
            }
        }
     }

当点击某一图片进行显示时,我们可以获取该图片目录下的所有图片,以便点击下一张按钮时可以连续的显示图片。

对于图片的放大,这里有一个放大按钮,连续点击可以放大到限定的倍数,这里也可以用鼠标的滚轮来控制,向上滚动是放大,向下滚动是缩小,缩小只能缩小到原图大小。这里对于图片的操作是用矢量图来操作的,以便保持图片不失真。图片的旋转,这个比较好做,只是简单的旋转问题,这里我会附上所有的代码供大家参考

主界面前台逻辑

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="690" Width="980" WindowStyle="None" AllowsTransparency="True" Background="Transparent" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen">
    <Border Name="topbd" Height="670" Width="960" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0" MouseLeftButtonDown="topbd_MouseLeftButtonDown">
        <Border.Effect>
            <DropShadowEffect Color="Black" BlurRadius="15" ShadowDepth="0" Opacity="0.5"/>
        </Border.Effect>
        <Grid Height="670" Width="960" Background="White" Name="NormalGd" Visibility="Visible">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" Height="30" Background="#3ea1e5">
                <Button  VerticalAlignment="Top" Width="58" Height="28" HorizontalAlignment="Left" Margin="5,0,0,0" Name="openbtn" Click="openbtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="打开文件" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Height="28" Width="28" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click" Margin="0,0,5,0">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Canvas  Canvas.Left="0" Canvas.Top="0" Width="28" Height="28" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent">
                                <Ellipse Name="closeellipse" Height="28" Width="28" Fill="#3ea1e5"/>
                                <Path x:Name="ph1" Fill="#ffffff" Data="M15.25 14l4.3-4.29L18.3 8.46 14 12.76 9.71 8.46 8.44 9.71 12.76 14 8.44 18.29l1.27 1.27L14 15.25l4.3 4.3 1.27-1.27Z">
                                    <Path.RenderTransform>
                                        <TranslateTransform X="0" Y="0"/>
                                    </Path.RenderTransform>
                                </Path>
                            </Canvas>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill"  Value="#e14315"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill" Value="#c02e03"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
            <Grid Grid.Row="1" HorizontalAlignment="Center" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="590"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <Border Grid.Row="0" Width="800" Height="540" Background="White" ClipToBounds="True" HorizontalAlignment="Center" VerticalAlignment="Bottom" BorderBrush="#494949" BorderThickness="1" CornerRadius="3">
                    <!--放置矢量图资源-->
                    <Canvas Background="White" MouseWheel="Canvas_MouseWheel" MouseEnter="Canvas_MouseEnter">
                        <Image Name="ScanImg" Stretch="None" Canvas.Left="308" Canvas.Top="208">
                            <Image.RenderTransform>
                                <MatrixTransform></MatrixTransform>
                            </Image.RenderTransform>
                        </Image>
                    </Canvas>
                </Border>
                <Button Name="enlarge" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="140,0,0,0" Click="enlarge_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/放大.jpg"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="fullscreen" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="220,0,0,0" Click="fullscreen_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/全屏.jpg"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="left" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="320,0,0,0" Click="left_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/左旋.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="right" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="420,0,0,0" Click="right_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/右旋.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="resite" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="520,0,0,0" Click="resite_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/还原放大.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="next" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="620,0,0,0" Click="next_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/next.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="delete" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="720,0,0,0" Click="delete_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/删除.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
        </Grid>
    </Border>
</Window>

主界面后台代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Forms;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string path = string.Empty;
        public string photoPath = string.Empty;
        public string pressedid = string.Empty;
        public string _id = string.Empty;
        public int _height;
        public int _width;
        public int height;
        public int width;
        public string pressedImgpath = string.Empty;
        List<FrameworkElement> _elementlist = new List<System.Windows.FrameworkElement>();
        private double _nScales = 5;  // 图片最大放大倍数,默认5倍
        FrameworkElement _element = new FrameworkElement();
        public double primaryHeight;
        public double primaryWidth;
        public string lastpressedid;
        const int MinMemorySize = 1024;
        List<string> imgs = new List<string>();//图片列表
        List<string> AllImgs = new List<string>();//图片列表
        int currentView = 0;
        double pressed = 1;
        public string ImagePath = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
            path = System.AppDomain.CurrentDomain.BaseDirectory;
            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
        }
        /// <summary>
        /// 按钮动作
        /// </summary>
        /// <param name="ev"></param>
        private void BtnEvent()
        {
            if (AllImgs.Count > 0)
            {
                if (currentView >= AllImgs.Count) { currentView = 0; }
                BitmapImage img = GetPictureImage(AllImgs[currentView]);
                ScanImg.Source = img;
                ScanImg.Width = img.Width;
                ScanImg.Height = img.Height;
                string title = AllImgs[currentView].Substring(AllImgs[currentView].LastIndexOf('\\') + 1);
                this.Title = title;
                currentView++;
            }
        }
        /// <summary>
        /// 获取指定路径的图片信息
        /// </summary>
        /// <param name="path">图片全路径</param>
        /// <returns></returns>
        private BitmapImage GetPictureImage(string path)
        {
            if (!File.Exists(path))
            {
                //CommonLog.log.Info("进入方法GetPictureImage(string path)中,图片路径不存在!参数path为:" + path);
                return null;
            }

FileStream fs = null;
            BitmapImage bmp = null;

try
            {
                fs = new FileStream(path, FileMode.Open);
                byte[] byData = new byte[fs.Length];
                fs.Read(byData, 0, byData.Length);
                fs.Close();

bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byData);
                bmp.EndInit();
            }
            catch (Exception ex)
            {
                bmp = null;
                //CommonLog.log.Error(string.Format("进入方法GetPictureImage(string path)中,获取图片信息失败,原因:{0},详细描述:{1},图片路径:{2}",
                //                                                   ex.Message, ex.StackTrace, path));
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

return bmp;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] commandLineArgs = Environment.GetCommandLineArgs();//

if (commandLineArgs.Length > 1)
            {
                string currentOpenedFile = Environment.GetCommandLineArgs()[1];//当前被打开的图片路径
                string _p = currentOpenedFile.Substring(0, currentOpenedFile.LastIndexOf('\\'));
                ImageFile hp = new ImageFile(_p);  //被打开的图片所在的目录
                imgs = hp.GetImgInfo;
                imgs.Remove(commandLineArgs[1]);
                AllImgs.Clear();
                AllImgs.Add(commandLineArgs[1]);
                for (int i = 0; i < imgs.Count; i++)
                {
                    AllImgs.Add(imgs[i]);
                }
                BtnEvent();
                ScanImg.SetValue(Canvas.LeftProperty,(400 - ScanImg.Width/2));
                ScanImg.SetValue(Canvas.TopProperty, (270 - ScanImg.Height/ 2));

}
        }

private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
            this.Close();
        }

private void enlarge_Click(object sender, RoutedEventArgs e)
        {
            pressed = pressed + 0.1;
            //描述鼠标滑轮滚动
            if (_elementlist != null && _elementlist.Count >= 100)
            {
                _elementlist.RemoveAt(0);
            }

FrameworkElement element = (FrameworkElement)ScanImg;
            element.Opacity = 1;
            Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix;

System.Windows.Point center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);

if (center.X < 20 || center.Y < 20)
            {
                element = _elementlist[50];
                matrix = ((MatrixTransform)element.RenderTransform).Matrix;
                center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
            }
            center = matrix.Transform(center);
            if (matrix.M11 * pressed >= _nScales || matrix.M22 * pressed >= _nScales)
            {
                matrix.M11 = _nScales;
                matrix.M22 = _nScales;
                return;
            }
            matrix.ScaleAt(pressed, pressed, center.X, center.Y);
            //matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y);
            //matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
            ((MatrixTransform)element.RenderTransform).Matrix = matrix;
            _element = element;
            _elementlist.Add(element);
        }
        /// <summary>
        /// 图片全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fullscreen_Click(object sender, RoutedEventArgs e)
        {
            DoubleAnimation daV = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(1)));
            daV.Completed += daV_Completed;
            this.BeginAnimation(UIElement.OpacityProperty, daV);
           
        }
        private void daV_Completed(object sender, EventArgs e)
        {
            FullImg fl = new WpfApplication1.FullImg(ScanImg.Source);
            fl.Owner = this;
            fl.QuitKey_show = new FullImg.QuitKey(QuitKey_show);
            fl.ShowDialog();
            DoubleAnimation daV1 = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(1)));
            fl.BeginAnimation(UIElement.OpacityProperty, daV1);
        }
        private void QuitKey_show()
        {
            DoubleAnimation daV1 = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(1)));
            this.BeginAnimation(UIElement.OpacityProperty, daV1);
        }
        private void left_Click(object sender, RoutedEventArgs e)
        {
            System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int angel = 90;
            Rotate.RotateImg(myBitmap, angel, AllImgs[currentView-1]);
            angel += 90;
            if (angel == 360)
            {
                angel = 90;
            }
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);
            ScanImg.Source = img;
            ScanImg.Width = img.Width;
            ScanImg.Height = img.Height;
            myBitmap.Dispose();
        }

private void right_Click(object sender, RoutedEventArgs e)
        {
            System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int angel = -90;
            Rotate.RotateImg(myBitmap, angel, AllImgs[currentView-1]);
            angel -= 90;
            if (angel == -360)
            {
                angel = -90;
            }
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);
            ScanImg.Source = img;
            ScanImg.Width = img.Width;
            ScanImg.Height = img.Height;
            myBitmap.Dispose();
        }

private void topbd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        /// <summary>
        /// 归位原图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resite_Click(object sender, RoutedEventArgs e)
        {
            ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
        }
        private Matrix _originMatrix;   // 初始矩阵
        private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
        {
         
            double val;   //描述鼠标滑轮滚动
            if (_elementlist != null && _elementlist.Count >= 100)
            {
                _elementlist.RemoveAt(0);
            }

FrameworkElement element = (FrameworkElement)ScanImg;
            element.Opacity = 1;
            Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix;

System.Windows.Point center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
          
            if (center.X < 20 || center.Y < 20)
            {
                element = _elementlist[50];
                matrix = ((MatrixTransform)element.RenderTransform).Matrix;
                center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
            }
            center = matrix.Transform(center);

// 不可以对原始图片进行缩小,即:缩放比例倍数不可小于1
            // if ((matrix.M11 * System.Math.Abs(val)) <= 1.0 || (matrix.M22 * System.Math.Abs(val)) <= 1.0)
            if ((double)e.Delta >= 0)
            {
                val = (double)e.Delta / 100;
                // 缩放最大不能大于5倍
                if (matrix.M11 * val >= _nScales || matrix.M22 * val >= _nScales)
                {
                    matrix.M11 = _nScales;
                    matrix.M22 = _nScales;
                    return;
                }
                matrix.ScaleAt(val, val, center.X, center.Y);
            }
            else
            {
               
                if (matrix.M11 * 0.7 <= 1 || matrix.M22 * 0.7 <= 1)
                {
                    ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
                    return;
                }
                matrix.ScaleAt(0.7, 0.7, center.X, center.Y);
            }
            //matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y);
            //matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
            ((MatrixTransform)element.RenderTransform).Matrix = matrix;
            _element = element;
            _elementlist.Add(element);
        }

private void Canvas_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            FrameworkElement element = (FrameworkElement)ScanImg;
            primaryHeight = element.ActualHeight;
            primaryWidth = element.ActualWidth;
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void delete_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);

string[] file = pressedImgpath.Split('\\');
            string filename = file[file.Length - 1];
            int index = filename.IndexOf('.');
            int length = filename.Length;
            string type = filename.Substring(index + 1, (length - index - 1));
            type = type + "图像";

System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int height = myBitmap.Height;
            int width = myBitmap.Width;
            string wh = width.ToString() + "×" + height.ToString();
            myBitmap.Dispose();

FileInfo f = new FileInfo(AllImgs[currentView-1]);
            double size = f.Length;

size = size / (double)MinMemorySize;
            string imgsize = GetCapacity(size);
            showtip st = new showtip(img, filename, type, wh, imgsize);
            st.Owner = this;
            st.ShowDialog();
            if (st.DialogResult == true)
            {
                if (f.Exists)
                {
                    ScanImg.Source = null;
                    f.Delete();
                }
            }
        }
       
        /// <summary>
        /// 将获得的容量KB转化为MB或GB
        /// </summary>
        /// <param name="_num"></param>
        /// <returns></returns>
        public string GetCapacity(double inputNum)
        {
            string num = string.Empty;
            double Dnum;
            double _num = (inputNum < 0) ? 0 : inputNum;
            if (_num < MinMemorySize)
            {
                _num = Math.Round(_num, MidpointRounding.AwayFromZero);
                num = _num.ToString() + "KB";
            }
            else if (_num < (MinMemorySize * MinMemorySize))
            {
                Dnum = (double)_num / (double)MinMemorySize;
                Dnum = Math.Round(Dnum, MidpointRounding.AwayFromZero);
                num = Dnum.ToString() + "MB";
            }
            else
            {
                Dnum = (double)_num / (double)(MinMemorySize * MinMemorySize);
                Dnum = Math.Round(Dnum, MidpointRounding.AwayFromZero);
                num = Dnum.ToString() + "GB";
            }

return num;
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openbtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog m_Dialog = new System.Windows.Forms.OpenFileDialog();
            m_Dialog.Multiselect = true;
            m_Dialog.Title = "请选择文件";
            m_Dialog.Filter = "所有文件(*.*)|*.*";
            DialogResult result = m_Dialog.ShowDialog();

if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            ImagePath = m_Dialog.FileName;
            if (!string.IsNullOrEmpty(ImagePath))
            {
                string _p = ImagePath.Substring(0, ImagePath.LastIndexOf('\\'));
                ImageFile hp = new ImageFile(_p);  //被打开的图片所在的目录
                imgs = hp.GetImgInfo;
                imgs.Remove(ImagePath);
                AllImgs.Clear();
                AllImgs.Add(ImagePath);
                for (int i = 0; i < imgs.Count; i++)
                {
                    AllImgs.Add(imgs[i]);
                }
                BtnEvent();
            }
        }

private void next_Click(object sender, RoutedEventArgs e)
        {
            if (AllImgs.Count < 2)
            {
                return;
            }
            BtnEvent();
        }
    }

}
提示界面

<Window x:Class="WpfApplication1.showtip"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="showtip" Height="220" Width="370" WindowStyle="None" AllowsTransparency="True" WindowStartupLocation="CenterScreen" Background="Transparent" Loaded="Window_Loaded">
    <Border Name="topbd" Height="200" Width="350" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0">
        <Border.Effect>
            <DropShadowEffect Color="Black" BlurRadius="15" ShadowDepth="0" Opacity="0.5"/>
        </Border.Effect>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="0" Background="#3ea1e5">
                <Button Height="30" Width="30" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Canvas  Canvas.Left="0" Canvas.Top="0" Width="28" Height="28" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent">
                                <Ellipse Name="closeellipse" Height="28" Width="28" Fill="#3ea1e5"/>
                                <Path x:Name="ph1" Fill="#ffffff" Data="M15.25 14l4.3-4.29L18.3 8.46 14 12.76 9.71 8.46 8.44 9.71 12.76 14 8.44 18.29l1.27 1.27L14 15.25l4.3 4.3 1.27-1.27Z">
                                    <Path.RenderTransform>
                                        <TranslateTransform X="0" Y="0"/>
                                    </Path.RenderTransform>
                                </Path>
                            </Canvas>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill"  Value="#e14315"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill" Value="#c02e03"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </StackPanel>
            <Grid Grid.Row="1" Background="White">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="32"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Image Grid.Row="0" Grid.Column="0" Source="Images/回收站.png" Height="30" Width="30" Stretch="UniformToFill"  HorizontalAlignment="Center" VerticalAlignment="Bottom" />
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="确实要把此文件放入回收站吗?" FontFamily="微软雅黑" FontSize="12" Foreground="#494949" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                    <Image Name="deleteImg" Source="Images/背景色1.png" Grid.Column="1" Grid.Row="1" Grid.RowSpan="4" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <TextBlock Grid.Column="1" Grid.Row="1" Name="ImgName"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="2" Name="ImgType"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="3" Name="ImgWH"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="4" Name="ImgSize"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                </Grid>
                <Button Grid.Row="1" Width="50" Height="20" FocusVisualStyle="{x:Null}" BorderThickness="0" Name="OkBtn" Click="OkBtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="确定" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Grid.Row="1" Width="50" Height="20" Margin="200,0,0,0" FocusVisualStyle="{x:Null}" BorderThickness="0" Name="CancelBtn" Click="CancelBtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="取消" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
        </Grid>
    </Border>
</Window>
后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// showtip.xaml 的交互逻辑
    /// </summary>
    public partial class showtip : Window
    {
        public showtip()
        {
            InitializeComponent();
        }
        public showtip( BitmapImage img,string filename,string filetype, string fileWH,string fileSize)
        {
            InitializeComponent();
            deleteImg.Source = img;
            ImgName.Text = filename;
            ImgType.Text = "项目类型:" + filetype;
            ImgWH.Text = "尺寸:" + fileWH;
            ImgSize.Text = "大小:" + fileSize;
        }

private void OkBtn_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FrameworkElement element = (FrameworkElement)deleteImg;
            ImgName.Margin = new Thickness(element.ActualWidth+5,0,0,0);
            ImgType.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
            ImgWH.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
            ImgSize.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
        }
    }
}
图片旋转相应方法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1
{
   public class Rotate
    {
        /// <summary>

/// 以逆时针为方向对图像进行旋转

/// </summary>

/// <param name="b">位图流</param>

/// <param name="angle">旋转角度[0,360](前台给的)</param>

/// <returns></returns>

public static Image RotateImg(Image b, int angle,string savepath)

{
            if (angle >= 0)
            {
                angle = angle % 360;
            }
            else
            {
                angle = (angle + 360) % 360;
            }

//弧度转换

double radian = angle * Math.PI / 180.0;

double cos = Math.Cos(radian);

double sin = Math.Sin(radian);

//原图的宽和高

int w = b.Width;

int h = b.Height;

int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));

int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));

//目标位图

Bitmap dsImage = new Bitmap(W, H);

System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//计算偏移量

Point Offset = new Point((W - w) / 2, (H - h) / 2);

//构造图像显示区域:让图像的中心与窗口的中心点一致

Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);

Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);

g.TranslateTransform(center.X, center.Y);

g.RotateTransform(360 - angle);

//恢复图像在水平和垂直方向的平移

g.TranslateTransform(-center.X, -center.Y);

g.DrawImage(b, rect);

//重至绘图的所有变换

g.ResetTransform();

g.Save();

g.Dispose();

//保存旋转后的图片

b.Dispose();

dsImage.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);

return dsImage;

}

//public Image RotateImg(string filename, int angle)

//{

//    return RotateImg(GetSourceImg(filename), angle);

//}

public static Image GetSourceImg(string filename)

{

Image img;

img = Bitmap.FromFile(filename);

return img;

}
        /// <summary>
        /// Resize图片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的宽度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留着,暂时未用</param>
        /// <returns>处理以后的图片</returns>
        public static Image KiResizeImage(Image bmp, int newW, int newH,string savepath)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                bmp.Dispose();
                b.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);
                return b;
            }
            catch
            {
                return null;
            }
        }
        public static Image pictureProcess(Image sourceImage, int targetWidth, int targetHeight,string path)
        {
            int width;//图片最终的宽
            int height;//图片最终的高
            try
            {
                System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
                Bitmap targetPicture = new Bitmap(targetWidth, targetHeight);
                Graphics g = Graphics.FromImage(targetPicture);
                g.Clear(Color.White);

//计算缩放图片的大小
                if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height > targetHeight)
                {
                    height = targetHeight;
                    width = (height * sourceImage.Width) / sourceImage.Height;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = sourceImage.Width;
                    height = sourceImage.Height;
                }
                else
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                    if (height > targetHeight)
                    {
                        height = targetHeight;
                        width = (height * sourceImage.Width) / sourceImage.Height;
                    }
                }
               // g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
               g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
                sourceImage.Dispose();
                targetPicture.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                return targetPicture;
            }
            catch (Exception ex)
            {

}
            return null;
        }
    }
}



wpf绘制图片查看器相关推荐

  1. JavaSwing图片绘制,实现简单的图片查看器

    刚学到JavaSwing图片绘制,于是自己做了个简易的图片查看器小程序,在这里分享给大家,请多多指教. 话不多说先上部分图: 绘制图片需要自定义一个控件,我们这里写一个继承自JPanel的类,重写pa ...

  2. java swing awt绘制一个图片查看器 图片显示 图片控件

    感谢 java图片查看器 的代码 java似乎没有一个名字叫图片控件的 控件,使用swing 的Label显示图片 他的代码如下: package swing.draw; import java.aw ...

  3. Qt 仿QQ图片查看器

    最近项目中,由于需要查看图片.看了网上写的各种图片查看器.感觉都没有QQ图片查看器那种界面好看一点.并且放大了可以移动图片.为此,想着仿QQ图片查看器自己写了一个,如图: 主要实现的功能有: 鼠标滚轮 ...

  4. 【React组件】写一个模仿蓝湖的图片查看器

    前言 最近公司让写一个可以自由拖拽放大的图片查看器,我寻思这还不简单,一顿操作猛如虎,俩小时后: 事实证明,一旦涉及到 DOM 的变换操作,如果很多细节考虑不全,抓过来就写,那基本就凉了.于是我仔细分 ...

  5. 图片html代码查看器,360度全景商品图片查看器

    360 Degrees Product Viewer360度全景商品图图片查看器是个非常简单的轻松展示图片全景插件. HTML Handle CSS .cd-product-viewer-wrappe ...

  6. 强大的jQuery图片查看器插件Viewer.js

    简介 Viewer.js 是一款强大的图片查看器 Viewer.js 有以下特点: 支持移动设备触摸事件 支持响应式 支持放大/缩小 支持旋转(类似微博的图片旋转) 支持水平/垂直翻转 支持图片移动 ...

  7. Win7图片查看器打印不了图片怎么办

    当我们想浏览电脑中的图片文件时,可以选择系统自带的图片查看器或者第三方看图工具打开,但是有些win7用户发现自己想通过windows图片查看器打印图片却没有反应,Win7图片查看器打印不了图片怎么办? ...

  8. 【javascript实现的图片查看器】仿lightbox

    一直就认为javascript是个好东西,一直想好好学习.学习当然也得有成果,在将近隔了一个月后终于有东西可写了. 如今,我用javascript做了个图片查看器. 先看效果图: 先介绍下功能: 1. ...

  9. win10照片查看器_图片打开方式中找不到Windows图片查看器怎么办

    如何在电脑中使用默认的windows图片查看器来打开图片进行查看的?有时我们可能无法找到Windows图片查看器工具,接下来小编就与大家分享,一种简单的利用windows图片查看器查看图片的具体方法. ...

  10. android 图片查看器

    android实现的图片查看器 public class MainActivity extends AppCompatActivity {private EditText et_new_path;pr ...

最新文章

  1. 为什么决策树相关的算法不需要标准化?那么那些模型需要标准化那?
  2. Wikioi 1020 孪生蜘蛛 Label:Floyd最短路
  3. html交互式添加线要素,HTML5 Canvas绘制交互式交叉线
  4. 计算机IO系列「一」零拷贝技术
  5. 你用哪种工具进行iOS app自动化功能测试?
  6. Lyft的TypeScript实践
  7. linux 文件列添加字段,如何在linux中加入所需列的文件?
  8. Android ------ handler 异步处理消息
  9. java treeset 重复_TreeSet判断重复元素解析及代码示例
  10. 捷径app 保存视频_Android N App捷径
  11. 整理一些计算机基础知识!
  12. 4.28考试总结(下午)
  13. Python批量下载MOOC课件
  14. 使用H5编写网页版象棋(源码)
  15. fps类游戏c语言源程序,95k的FPS游戏!用C++和汇编编写
  16. 古琴十大名曲——唐畅古琴
  17. 算法-舍弃不吉利数字
  18. Android10.0 startService启动过程
  19. C++实现多线程及其三种方法实现多线程同步
  20. Socket编程、协议理解

热门文章

  1. 有哪些不错的数学、物理类的「闲书」?
  2. JS入门到精通完整版
  3. 元宇宙,是忽悠还是未来
  4. linux安装谷歌浏览器(Chrome)
  5. linux 123端口,关闭123端口和1900端口的方法
  6. 堪称Python入门新华字典的《Python背记手册》高清无码版,开源免费下载
  7. 阮一峰ES6入门读书笔记(十五):Class
  8. FLV格式解析及其解析器的实现
  9. python调用大漠插件寻路_python调用大漠插件或天使插件
  10. 2021最新阿里Java面经