我试图使用WritableBitmap对位图images.But进行像素级的操作,我无法得到它,我想做的是在我用位图分配Image.Source属性之后操作WritableBitmap的像素数据。我在谷歌上搜索到,唯一找到的是调用bitmap.Invalidate()方法,但似乎不推荐它,因为我在WritableBitmap class.following中找不到这个方法,就是我用来更新图像的代码,但没有运气:
wbitmap.Lock();
wbitmap.WritePixels(rect, pixels, stride, 0);
wbitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
wbitmap.Unlock();
//given that i've already assigned image.Source with "wbitmap"
image.InvalidateVisual();对此有什么想法吗?
编辑
我希望任何其他方式的建议,快速 2D绘图在WPF更好的WritableBitmap。
发布于 2017-01-24 07:12:46
下面的简单示例演示如何在将WriteableBitmap分配给图像控件的Source属性时继续编写它。
XAML就是这样的:
<Window ...>
<Grid>
<Image x:Name="image"/>
</Grid>
</Window>在代码后面有一个计时器,它以随机像素的颜色值每秒覆盖WriteableBitmap十次。请注意,您必须允许Visual项目属性中的不安全代码(在Build选项卡中)。
或者,对于Lock/AddDirtyRect/Unlock,您也可以调用writePixels。但是,Lock方法还允许另一个非UI线程写入BackBuffer。
public partial class MainWindow : Window
{
private readonly WriteableBitmap bitmap
= new WriteableBitmap(100, 100, 96, 96, PixelFormats.Bgr32, null);
public MainWindow()
{
InitializeComponent();
image.Source = bitmap;
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.1) };
timer.Tick += OnTimerTick;
timer.Start();
}
private unsafe void OnTimerTick(object sender, EventArgs e)
{
int pixelValue = (int)DateTime.Now.Ticks & 0xFFFFFF;
bitmap.Lock();
var backBuffer = bitmap.BackBuffer;
for (int y = 0; y < bitmap.PixelHeight; y++)
{
for (int x = 0; x < bitmap.PixelWidth; x++)
{
var bufPtr = backBuffer + bitmap.BackBufferStride * y + x * 4;
*((int*)bufPtr) = pixelValue;
}
}
bitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight));
bitmap.Unlock();
}
}https://stackoverflow.com/questions/41814696
复制相似问题