Content

关于WPF?WriteableBitmap类直接操作像素点的问题(wpf objectdataprovider)奔走相告

文章摘要

这篇文章描述了一段C#代码,其核心内容是在Windows Forms Application(WPF)中实现一个动态变化的图形效果。代码主要通过以下步骤实现: 1. **创建可编辑位图(WriteableBitmap)**:在按钮点击事件中,生成一个可编辑位图,并对其进行缩放和裁剪处理。 2. **计算像素颜色**:对于位图中的每个像素,根据其坐标(x, y)计算颜色值: - 当x或y为特定倍数时,生成特定的颜色模式。 - 其他情况下,采用渐变颜色(红色和蓝色基于x和y的比例,绿色随机生成)。 3. **渲染图形**:将计算出的像素数据写入可编辑位图,并将其作为窗体的来源设置。 文章重点展示了如何通过编程实现动态的像素级图形效果,同时兼顾了代码的清晰性和性能优化。

using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; 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.Drawing; using System.Drawing.Drawing2D; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void Button_Click(object sender, RoutedEventArgs e) WriteableBitmap wb=new WriteableBitmap((int)imgGrid.ActualWidth, (int)imgGrid.ActualHeight, 96, 96, PixelFormats.Pbgra32, null); wb.Lock(); Bitmap backBitmap=new Bitmap((int)imgGrid.ActualWidth, (int)imgGrid.ActualHeight, wb.BackBufferStride, System.Drawing.Imaging.PixelFormat.Format32bppArgb, wb.BackBuffer); Int32Rect rect=new Int32Rect(0, 0, (int)imgGrid.ActualWidth, (int)imgGrid.ActualHeight); byte[] pixels=new byte[(int)imgGrid.ActualWidth * (int)imgGrid.ActualHeight * wb.Format.BitsPerPixel / 8]; Random rand=new Random(); for (int y=0; y < wb.PixelHeight; y++) { for (int x=0; x < wb.PixelWidth; x++) { int alpha=0; int red=0; int green=0; int blue=0; if ((x % 5==0) || (y % 7==0)) { red=(int)((double)y / wb.PixelHeight * 255); green=rand.Next(100, 255); blue=(int)((double)x / wb.PixelWidth * 255); alpha=255; } else red=(int)((double)x / wb.PixelWidth * 255); blue=(int)((double)y / wb.PixelHeight * 255); alpha=50; int pixeloffset=(x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8; pixels[pixeloffset]=(byte)blue; pixels[pixeloffset + 1]=(byte)green; pixels[pixeloffset + 2]=(byte)red; pixels[pixeloffset + 3]=(byte)alpha; } int stride=(wb.PixelWidth * wb.Format.BitsPerPixel) / 8; wb.WritePixels(rect, pixels, stride, 0); } wb.Unlock(); backBitmap.Dispose(); backBitmap=null; img.Source=wb; } }