本文主要是介绍WPF 晚上吃什么 制作gif动图,截图晚上吃什么,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天看到了一个类似这样的gif,截图来决定晚上吃什么,于是动手自己写一个,生成如此Gif的程序
github:https://github.com/442040292/WhatForDinner 完整的项目、虽然是个简单的小程序
需要使用到这个dll: Gif.Components.dll
直接上代码:
主页:
<Window x:Class="WhatForDinner.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:WhatForDinner"mc:Ignorable="d" x:Name="uc"Title="MainWindow" Height="450" Width="800"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="200"/><ColumnDefinition Width="1*"/></Grid.ColumnDefinitions><Button Content="解析并添加" Click="AddNewItem_Click" HorizontalAlignment="Left" Margin="37,133,0,0" VerticalAlignment="Top" Width="100" Height="41"/><TextBox x:Name="newItemString" HorizontalAlignment="Left" Height="115" TextWrapping="Wrap" Text="米线,麻辣烫,黄焖鸡,炒菜,饭团,麻辣香锅,拌面" VerticalAlignment="Top" Width="200"/><Button x:Name="button1" Content="创建" Click="Create_Click" HorizontalAlignment="Left" Margin="37,209,0,0" VerticalAlignment="Top" Width="100" Height="36"/><ScrollViewer Grid.Column="1" Grid.ColumnSpan="2"><ItemsControl ItemsSource="{Binding ItemSource,ElementName=uc}" ><ItemsControl.ItemTemplate><DataTemplate><Button Content="{Binding .}" Click="RemoveItem_Click"/></DataTemplate></ItemsControl.ItemTemplate><ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel/></ItemsPanelTemplate></ItemsControl.ItemsPanel></ItemsControl></ScrollViewer><TextBox x:Name="outputPath" HorizontalAlignment="Left" Height="67" Margin="0,352,0,0" TextWrapping="Wrap" Text="D://mygif.gif" VerticalAlignment="Top" Width="200"/></Grid>
</Window>
后面:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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;namespace WhatForDinner
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();ItemSource = new ObservableCollection<string>();}public ObservableCollection<string> ItemSource{get { return (ObservableCollection<string>)GetValue(ItemSourceProperty); }set { SetValue(ItemSourceProperty, value); }}// Using a DependencyProperty as the backing store for ItemSource. This enables animation, styling, binding, etc...public static readonly DependencyProperty ItemSourceProperty =DependencyProperty.Register("ItemSource", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(null));private string SavePath = @"D://mygif.gif";private void Create_Click(object sender, RoutedEventArgs e){Helper.CreateGif(ItemSource, SavePath);outputPath.Text = SavePath;}private void AddNewItem_Click(object sender, RoutedEventArgs e){string newiRTEMS = newItemString.Text;if (!string.IsNullOrEmpty(newiRTEMS)){var items = newiRTEMS.Split(',', ',');foreach (var item in items){ItemSource.Add(item);}}var distList = ItemSource.Distinct().ToList();ItemSource = new ObservableCollection<string>(distList);}private void RemoveItem_Click(object sender, RoutedEventArgs e){var button = sender as Button;var content = button.Content.ToString();var removeItems = ItemSource.Where(x => x == content).ToList();foreach (var item in removeItems){if (ItemSource.Any(x => x == item)){ItemSource.Remove(item);}}}}
}
帮助类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;using Gif.Components;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;namespace WhatForDinner
{public class Helper{public static void CreateGif(IEnumerable<string> newItems, string savePath){if (newItems.Count() <= 0){return;}List<System.Drawing.Image> images = new List<System.Drawing.Image>();var maxWidth = newItems.Max(x => x.Length) * 3 * 14;var maxHeight = 100;foreach (var item in newItems){var image = FillRectangle(item, maxWidth, maxHeight);images.Add(image);}ConvertJpgToGif(images, savePath, 1, maxWidth, maxHeight);}/// <summary>/// 多张图片转成一张gif图片/// </summary>/// <param name="imageFilePaths">图片路径,放到一个数组里面</param>/// <param name="gifPath">生成的gif图片路径</param>/// <param name="time">每一帧图片间隔时间</param>/// <param name="w">生成的gif图片宽度</param>/// <param name="h">生成的gif图片高度</param>/// <returns></returns>public static bool ConvertJpgToGif(List<System.Drawing.Image> images, string gifPath, int time, int w, int h){try{AnimatedGifEncoder e = new AnimatedGifEncoder();e.Start(gifPath);e.SetDelay(time);//0:循环播放 -1:不循环播放e.SetRepeat(0);for (int i = 0, count = images.Count; i < count; i++){//e.AddFrame(Image.FromFile(Server.MapPath(imageFilePaths[i])));System.Drawing.Image img = images[i];//如果多张图片的高度和宽度都不一样,可以打开这个注释img = ReSetPicSize(img, w, h);e.AddFrame(img);}e.Finish();return true;}catch (Exception ex){return false;}}/// <summary>/// 重新调整图片的大小,使其满足要求/// </summary>/// <param name="image"></param>/// <param name="newWidth"></param>/// <param name="newHeight"></param>/// <returns></returns>public static Image ReSetPicSize(Image image, int newWidth, int newHeight){Bitmap bmp = new Bitmap(image);try{Bitmap b = new Bitmap(newWidth, newHeight);Graphics g = Graphics.FromImage(b);// 插值算法的质量 g.InterpolationMode = InterpolationMode.HighQualityBicubic;g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, newWidth, newHeight), new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);g.Dispose();// return b;Image img = (Image)b;// MessageBox.Show("Width"+img.Width.ToString() + "Height:" + img.Height.ToString());return img;}catch{return null;}}/// <summary>/// 在图片中绘制 矩形/// </summary>/// <param name="image"></param>/// <param name="x"></param>/// <param name="y"></param>/// <param name="width"></param>/// <param name="height"></param>public static System.Drawing.Image FillRectangle(string text, int rectWith, int rectHeight){Bitmap b = new Bitmap(rectWith, rectHeight);System.Drawing.Image image = b;//b.Save("aa.jpg", ImageFormat.Jpeg);Graphics graphics = Graphics.FromImage(image);graphics.FillRectangle(new SolidBrush(System.Drawing.Color.White), new RectangleF(0, 0, rectWith, rectWith));graphics.DrawString(text, new Font("微软雅黑", 14), new SolidBrush(System.Drawing.Color.Black), rectWith / 2, rectHeight / 2, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });//红色的圈显示 点击位置graphics.Flush();graphics.Dispose();return image;}}
}
小技巧: 为了不附带dll 只用一个 exe 方便转发 使用直接 把dll嵌入到exe里面去了
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;namespace WhatForDinner
{/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;}private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args){string[] embedDll = new string[] { "Gif.Components" };string resourceName = "WhatForDinner." + new AssemblyName(args.Name).Name + ".dll";using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)){if (stream != null){byte[] assemblyData = new byte[stream.Length];stream.Read(assemblyData, 0, assemblyData.Length);return Assembly.Load(assemblyData);}else{return null;}}}}
}
OK 再次提醒晚上吃啥
这篇关于WPF 晚上吃什么 制作gif动图,截图晚上吃什么的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!