WPF中WriteableBitmap显示全黑异常问题求助
问题解决:WPF/.NET 8中Gray8格式WriteableBitmap直接显示全黑
核心原因
WriteableBitmap写入像素后,未主动通知WPF渲染系统更新像素内容。虽然保存为PNG时编码器会完整读取缓冲区,但WPF默认不会自动检测BackBuffer的修改,需要显式标记脏区域触发刷新。
修复代码
修改CreateLineWeightImage方法,在Unlock()前添加AddDirtyRect调用,标记整个位图为脏区域:
public BitmapSource CreateLineWeightImage() { if (LineWeights == null) throw new InvalidOperationException("Must GetLineWeights first"); WriteableBitmap lineWeights = new WriteableBitmap(LineWeightImageWidth, OriginalImage.PixelHeight, 96, 96, PixelFormats.Gray8, null); lineWeights.Lock(); unsafe { for (int y = 0; y < lineWeights.PixelHeight; ++y) { for (int x = 0; x < LineWeightImageWidth; ++x) { byte* PixelPtr = (byte*)lineWeights.BackBuffer + y * lineWeights.BackBufferStride + x; *((byte*)PixelPtr) = (byte)LineWeights[y]; } } } // 标记整个位图区域为脏,通知WPF更新显示 lineWeights.AddDirtyRect(new Int32Rect(0, 0, lineWeights.PixelWidth, lineWeights.PixelHeight)); lineWeights.Unlock(); LineWeightsImage = lineWeights; return lineWeights; }
额外说明
- 关于重新保存加载不更新的问题:这是WPF对本地文件的缓存机制导致的,可通过加载时添加随机查询参数(如
new Uri("file:///xxx.png?r=" + Guid.NewGuid()))绕过缓存,或保存前删除旧文件再写入新文件。 - 代码中每行所有x像素都写入同一个
LineWeights[y],如果这是业务需求(生成垂直灰度条)则无需调整;若需按x索引对应不同灰度值,需修改为LineWeights[y * LineWeightImageWidth + x]或匹配业务逻辑的取值方式。
内容的提问来源于stack exchange,提问作者user1812615
相关产品推荐
相关产品推荐

