WPF 制作电子相册浏览器

简介: 原文:WPF 制作电子相册浏览器   周末的时候,闲着无聊,做了一个电子相册浏览器。比较简单。界面如下: 主要部分代码如下: MainWindow.xaml ...
原文: WPF 制作电子相册浏览器

   周末的时候,闲着无聊,做了一个电子相册浏览器。比较简单。界面如下:

主要部分代码如下:

MainWindow.xaml

<local:HeaderedWindow x:Class="PictureMagic.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:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
        xmlns:dxcore="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PictureMagic"
        mc:Ignorable="d"
        Title="电子相册浏览器" Height="700" Width="900" Closing="HeaderedWindow_Closing">
    <local:HeaderedWindow.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Themes/Style.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </local:HeaderedWindow.Resources>
    <Grid x:Name="gridCtr">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="101"/>
            <ColumnDefinition Width="101"/>
            <ColumnDefinition Width="101"/>
            <ColumnDefinition Width="544*"/>
            <ColumnDefinition Width="45*"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="53*"/>
            <RowDefinition Height="639*"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Grid.Column="0"  Width="100" HorizontalAlignment="Left" Content="选择图片" Style="{DynamicResource btnStyle}" Click="bntSelectPhoto_Click"/>
        <Button Grid.Row="0" Grid.Column="1"  Width="100" HorizontalAlignment="Left" Content="选择音乐" Style="{DynamicResource btnStyle}" Click="bntSelectMusic_Click"/>
        <Button Grid.Row="0" Grid.Column="2"  Width="100" HorizontalAlignment="Left" Content="开始欣赏" Style="{DynamicResource btnStyle}" Click="bntViewPhotos_Click"/>
        <Image Grid.Row="0" Grid.Column="3" Source="Image/yezi.png" HorizontalAlignment="Center" VerticalAlignment="Stretch" Margin="115,0,225,0" Width="204"/>
        <dxdo:LayoutPanel x:Name="panelLeft"  Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Grid.ColumnSpan="3" 
                          ShowCloseButton="False" ShowControlBox="False" ShowMaximizeButton="False" ShowPinButton="False" ShowRestoreButton="False" Background="{x:Null}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <ListBox x:Name="imageListBox" Background="{x:Null}" Grid.Column="0">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Image Width="101" Height="101" Source="{Binding Path=ImagePath}">
                            </Image>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
                <ListBox x:Name="musicListBox" Background="{x:Null}" Grid.Column="1">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=MusicTitle}" Style="{DynamicResource MusicStyle}" MouseLeftButtonDown ="TextBlock_MouseLeftButtonDown">
                            </TextBlock>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </dxdo:LayoutPanel>
        
        <dxdo:LayoutPanel x:Name="panelShow"  Grid.Column="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Grid.ColumnSpan="2" 
                          ShowCloseButton="False" ShowControlBox="False" ShowMaximizeButton="False" ShowPinButton="False" ShowRestoreButton="False" Background="{x:Null}">
            <Image x:Name="picShow" Grid.Row="1" Grid.Column="3" Source="{Binding Path=ImagePath}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.ColumnSpan="2"></Image>
        </dxdo:LayoutPanel>

    </Grid>
</local:HeaderedWindow>

  MainWindow.xaml.cs

using System;
using System.Collections.Generic;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Windows.Threading;
using System.Drawing;
using System.Xml.Linq;

namespace PictureMagic
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : HeaderedWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            m_picureInfoList = new List<PicutureInfo>();
            m_musicList = new List<MusicInfo>();
            this.picShow.DataContext = m_picutureInfoViewModel;

            Timer_Init();
            InitShowImageTimer();
            InitMediaPlay();
            ReadXML();

            if (!m_strPictureFolder.Equals(""))
            {
                SearchImage(m_strPictureFolder);
                imageListBox.ItemsSource = m_picureInfoList;
                if (m_picureInfoList.Count > 0)
                {
                    m_picutureInfoViewModel.ImagePath = m_picureInfoList[0].ImagePath;
                    ShowImage(m_picutureInfoViewModel.ImagePath);
                }
            }

            if (!m_strMusicFolder.Equals(""))
            {
                SearchMusic(m_strMusicFolder);
                musicListBox.ItemsSource = m_musicList;
            }
        }
        /**  图片信息 **/
        private List<PicutureInfo> m_picureInfoList = null;
        private int m_ImageIndex = 0;
        private string m_strPictureFolder = "";
        private PicutureInfo m_picutureInfoViewModel = new PicutureInfo();
        private bool m_bPicturePlay = false;
        private bool m_bOnePictureFinished = false;

        /**  音乐信息 **/
        private MediaElement mediaPlayer = new MediaElement();
        private List<MusicInfo> m_musicList = null;
        private int m_MusicIndex = 0;
        private string m_strMusicFolder = "";

        /*** 用于显示图片动画 ***/
        private int m_iRectSize = 100;          //设置矩形的大小
        private int m_iCurRectSize = 0;        //矩形的初始宽度
        private PathGeometry m_pathGeometry = new PathGeometry();
        private DispatcherTimer m_imageRectTimer = new DispatcherTimer();
        private int m_imageWidth = 0;
        private int m_imageHeight = 0;

        private DispatcherTimer m_timer = new DispatcherTimer();//创建定时器对象

        void Timer_Tick(object sender, EventArgs e)
        {
            if (m_bOnePictureFinished)
            {
                if (m_ImageIndex + 1 >= m_picureInfoList.Count)
                {
                    m_ImageIndex = 0;
                }
                else
                {
                    m_ImageIndex++;
                }
                m_picutureInfoViewModel.ImagePath = m_picureInfoList[m_ImageIndex].ImagePath;
                ShowImage(m_picutureInfoViewModel.ImagePath);
            }
        }

        void Timer_Init()
        {
            m_timer.Tick += new EventHandler(Timer_Tick); //添加事件,定时到事件  
            m_timer.Interval = TimeSpan.FromMilliseconds(3000);//设置定时长  
        }
        void Timer_Stop()
        {
            m_timer.Stop();
        }

        void Timer_Start()
        {
            m_timer.Start();
        }
        private void InitMediaPlay()
        {
            mediaPlayer.LoadedBehavior = MediaState.Manual;  //设置为手动控制  
            mediaPlayer.UnloadedBehavior = MediaState.Manual;
            mediaPlayer.IsHitTestVisible = true;
            mediaPlayer.MediaEnded += new RoutedEventHandler(me_MediaEnded);
            gridCtr.Children.Add(mediaPlayer);
        }
        private void me_MediaEnded(object sender, RoutedEventArgs e)
        {
            StopMusic();
            if (m_MusicIndex + 1 >= m_musicList.Count)
            {
                m_MusicIndex = 0;
            }
            else
            {
                m_MusicIndex++;
            }
            PlayMusic();
        }

        private void PlayMusic()
        {
            Uri uri = new Uri(m_musicList[m_MusicIndex].MusicPath, UriKind.Relative);
            mediaPlayer.Source = uri;

            musicListBox.Focus();
            musicListBox.SelectedIndex = m_MusicIndex;
            mediaPlayer.Play();
        }
        private void StopMusic()
        {
            mediaPlayer.Stop();
        }

        private void SearchImage(string path)
        {
            m_picureInfoList.Clear();
            DirectoryInfo folder = new DirectoryInfo(path);

            foreach (FileInfo file in folder.GetFiles("*.*"))
            {
                if (IsPhotoFile(file.Extension))
                {
                    PicutureInfo Info = new PicutureInfo();
                    Info.ImagePath = file.FullName;
                    m_picureInfoList.Add(Info);
                }
            }
        }

        private void SearchMusic(string path)
        {
            m_musicList.Clear();
            DirectoryInfo folder = new DirectoryInfo(path);

            foreach (FileInfo file in folder.GetFiles("*.*"))
            {
                if (IsMusicFile(file.Extension))
                {
                    MusicInfo Info = new MusicInfo();
                    Info.MusicPath = file.FullName;
                    Info.MusicTitle = file.Name;
                    m_musicList.Add(Info);
                }
            }
        }

        private bool IsMusicFile(string extension)
        {
            string[] exArray = { ".MP3", ".WAVE", ".WMA", ".MIDI" };
            foreach (string strExe in exArray)
            {
                if (extension.ToUpper().Equals(strExe))
                {
                    return true;
                }
            }
            return false;
        }

        private bool IsPhotoFile(string extension)
        {
            string[] exArray = { ".PNG", ".JPG", ".BMP", ".GIF", ".JPEG"};
            foreach(string strExe in exArray)
            {
                if (extension.ToUpper().Equals(strExe))
                {
                    return true;
                }
            }
            return false;
        }

        private void bntSelectPhoto_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择照片目录路径";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                m_strPictureFolder = foldPath;
                SearchImage(foldPath);
                imageListBox.ItemsSource = m_picureInfoList;
                if (m_picureInfoList.Count > 0)
                {
                    m_picutureInfoViewModel.ImagePath = m_picureInfoList[0].ImagePath;
                    ShowImage(m_picutureInfoViewModel.ImagePath);
                }
            }
        }

        private void bntSelectMusic_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择音乐目录路径";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                m_strMusicFolder = foldPath;
                SearchMusic(foldPath);
                musicListBox.ItemsSource = m_musicList;
            }
        }
        private void bntViewPhotos_Click(object sender, RoutedEventArgs e)
        {
            if (m_musicList.Count > 0)
            {
                PlayMusic();
            }
            if (m_picureInfoList.Count> 0)
            {
                Timer_Start();
                m_bPicturePlay = true;
            }
        }

        private void InitShowImageTimer()
        {
            m_imageRectTimer.Interval = TimeSpan.FromMilliseconds(1);
            m_imageRectTimer.Tick += new EventHandler(ImageRectTimer_Tick);
        }

        private void ShowImage(string strImagePath)
        {
            Bitmap pic = new Bitmap(m_picutureInfoViewModel.ImagePath);

            m_imageWidth = pic.Size.Width; // 图片的宽度
            m_imageHeight = pic.Size.Height; // 图片的高度
            // m_imageRectTimer.Stop();
            m_bOnePictureFinished = false;
            if (m_pathGeometry != null)
            {
                m_pathGeometry.Clear();
            }
            m_imageRectTimer.Start();
        }

        private void ImageRectTimer_Tick(object sender, EventArgs e)
        {
            if (m_iCurRectSize <= m_iRectSize)
            {
                for (int i = 0; i < (int)Math.Ceiling(m_imageWidth /(double)m_iRectSize); i++)
                {
                    RectangleGeometry rg = new RectangleGeometry();

                    //设置矩形区域大小
                    rg.Rect = new Rect(i * m_iRectSize, 0, m_iCurRectSize, m_imageHeight);
                    //合并几何图形
                    m_pathGeometry = Geometry.Combine(m_pathGeometry, rg, GeometryCombineMode.Union, null);
                    picShow.Clip = m_pathGeometry;
                }
                m_iCurRectSize++;
            }
            else
            {
                m_imageRectTimer.Stop();
                m_iCurRectSize = 0;
                m_bOnePictureFinished = true;
            }
        }

        private void HeaderedWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (m_musicList.Count > 0)
            {
                StopMusic();
            }
            SaveXML();
        }

        private void SaveXML()
        {
            try
            {
                string strPath = string.Format("{0}\\PictureMagic.xml", System.Windows.Forms.Application.StartupPath);
                XDocument xDoc = new XDocument();
                XElement xRoot = new XElement("Settings");
                xDoc.Add(xRoot);

                XElement pf = new XElement("PictureFolder");
                pf.Value = m_strPictureFolder;

                XElement mf = new XElement("MusicFolder");
                mf.Value = m_strMusicFolder;

                xRoot.Add(pf, mf);
                xDoc.Save(strPath);
            }catch(Exception)
            {

            }
        }

        private void ReadXML()
        {
            string strPath = string.Format("{0}\\PictureMagic.xml", System.Windows.Forms.Application.StartupPath);
            try
            {
                XDocument xDoc = XDocument.Load(strPath);

                XElement pf = xDoc.Root.Element("PictureFolder");
                m_strPictureFolder = pf.Value;

                XElement mf = xDoc.Root.Element("MusicFolder");
                m_strMusicFolder = mf.Value;
            }
            catch (Exception)
            {

            }
        }

        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount>= 2)
            {
                int selectIndex = musicListBox.SelectedIndex;
                if (selectIndex >= 0)
                {
                    StopMusic();
                    m_MusicIndex = selectIndex;
                    PlayMusic();

                    if (!m_bPicturePlay)
                    {
                        Timer_Start();
                        m_bPicturePlay = true;
                    }
                }
            }
        }
    }
}

  

目录
相关文章
|
安全 C# 定位技术
WPF:WebBrowser提示 为帮助保护你的安全,您的Web浏览器已经限制此文件显示可能访问您的计算机的活动内容
原文:WPF:WebBrowser提示 为帮助保护你的安全,您的Web浏览器已经限制此文件显示可能访问您的计算机的活动内容 版权声明:本文为博主原创文章,未经博主允许可以随意转载 https://blog.
3145 0
|
C# 前端开发 Android开发
WPF 客户端浏览器 添加Loading加载进度
原文:WPF 客户端浏览器 添加Loading加载进度 在windows开发界面时,使用浏览器来请求和显示网页内容,是比较常见的。 但是在请求网页内容时,因网速或者前端功能复杂加载较慢,亦或者加载时遇到各种问题,如空白/黑屏/加载不完整/证书问题等。
1724 0
|
C# iOS开发
WPF触控程序开发(三)——类似IPhone相册的反弹效果
原文:WPF触控程序开发(三)——类似IPhone相册的反弹效果      用过IPhone的都知道,IPhone相册里,当图片放大到一定程度后,手指一放,会自动缩回,移动图片超出边框后手指一放,图片也会自动缩回,整个过程非常和谐、自然、精确,那么WPF能否做到呢,答案是肯定的。
1012 0
|
Web App开发 JavaScript C#
在WPF中使用CefSharp嵌入浏览器
原文:在WPF中使用CefSharp嵌入浏览器 日常开发中,我们需要将一些Web页面嵌入到桌面客户端软件中。下面我们使用CefSharp嵌入浏览器来实现。  首先先介绍一下CefSharp嵌入式浏览器,它是基于Google浏览器的一个组件,我们可以在WPF/WinForm客户端软件中使用它。
2463 0
|
Web App开发 C# Android开发
WPF 使用 Edge 浏览器
原文:WPF 使用 Edge 浏览器 本文告诉大家如何使用 Windows Community Toolkit 的新控件,在 WPF 使用 Edge 浏览器 首先需要通过 VisualStudio 创建 WPF 项目。
1360 0
|
C# 数据可视化 容器
WPF自适应可关闭的TabControl 类似浏览器的标签页
原文:WPF自适应可关闭的TabControl 类似浏览器的标签页 效果如图:   虽然说是自适应可关闭的TabControl,但TabControl并不需要改动,不如叫自适应可关闭的TabItem.
2122 0
|
C# Windows Android开发
用WPF做一个简易浏览器
微软的WPF(Windows Presentation Foundation)是目前Windows平台上最好用的图形界面框架了。如果想在Windows平台上编写图形界面程序,而且没有跨平台且性能需求比较高,而且对C#语言比较熟悉,那么WPF就是最适合你的了。
1083 0
|
C# C++
WPF SpreadSheetGear电子表单
我们经常会碰到生成Excel 界面并在其上操作的功能开发。 比如如下界面,我们需要在菜单里添加一个菜单按钮“Columns To Rows Transform" 功能是对多列批量转成多行. 我们可以通过Interop组件,在其中添加菜单附加功能,这个在之后的随笔中我会写个Demo,供大家查看。
919 0
|
Shell Linux Windows
Shell脚本生成网页版相册浏览器
今天学到了一招,那就是使用脚本制作一款网页版相册浏览器。先上图吧。 必备基础 操作系统: 以linux为内核的操作系统都行 编程语言:Shell(bash)脚本,相关基础知识即可 下载工具:wget 图片处理工具: ImageMagicK, 解压缩工具 : rar ,bzip都行 额外技能:一些基本的Linux操作命令,如此即可。
1148 0
|
Web App开发 C# Windows
浏览器扩展系列————在WPF中定制WebBrowser快捷菜单
原文:浏览器扩展系列————在WPF中定制WebBrowser快捷菜单 关于如何定制菜单可以参考codeproject上的这篇文章:http://www.codeproject.com/KB/books/0764549146_8.aspx?fid=13574&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26#xx0xx 本文主要讲述如何在这篇文章中的ShowContextMenu方法中弹出自己的ContextMenu。
1036 0