我有一个 WPF 应用程序,其中包含 Image
控件。
我正在使用 WriteableBitmap
更新 Image.source
,但我不明白为什么我会看到这种奇怪的行为:我的图像分成两部分,顶部缓慢移动以相当缓慢的速度在周期中触底。
我不明白为什么会这样。顶部和底部实际上是同一帧,因为我可以在两者中看到实时更新。
我的代码:
public MainWindow()
{
InitializeComponent();
InitVideo();
image.Source = frame;
}
private void InitVideo
{
/// .... some other init stuff ...
frame = new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
rgbch = new byte[stride * height];
dataProc = new System.Threading.Thread(ReadData);
dataProc.Start();
}
// in separate thread
private void ReadData()
{
while (rxVideo)
{
for (int i = 0; i < rgbch.Length; i += stride)
{
pipe.Read(rgbch, i, stride);
}
Application.Current.Dispatcher.Invoke(() =>
{
frame.Lock();
frame.WritePixels(new Int32Rect(0, 0, width, height), rgbch, stride, 0);
frame.Unlock();
});
}
我尝试使用 frame.dispatcher.invoke
-> 同样的结果。
尝试了 Marshal.Copy
-> 同样的结果..
最佳答案
我找到了问题的根源。
这是我的线程内代码造成的
for (int i = 0; i < rgbch.Length; i += stride)
{
pipe.Read(rgbch, i, stride);
}
rgbch
被设置为 writablebitmap backbuffer 的源,所以当我在其中写入新数据时,更新速度很慢,所以我得到了奇怪的自上而下更新。
我只是做了 pipe.read(rgbch, 0, rgbch.Length)
并且它在图像中没有任何边界的情况下运行得更快。
关于c# - 为什么我的图片从上到下逐行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39253115/