1. 程式人生 > >WPF 制作電子相冊瀏覽器

WPF 制作電子相冊瀏覽器

source sharp 路徑 core them ats photos vertical raw

原文: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;
                    }
                }
            }
        }
    }
}

  

WPF 制作電子相冊瀏覽器