首页 > 解决方案 > C# PictureBox.SizeMode = 分配新图像时缩放不重绘

问题描述

我正在从事一个使用 ONVIF 的闭路电视项目。我使用“ONVIF 设备管理器”项目提供的 Winform 示例从相机获取视频帧。(你可以在这里找到它)如果我连接到一台相机,它工作正常。但是,如果我连接到六个摄像头,当我在 DrawFrame() 中分配新图像时,某些图片框不会重绘。所附图片中的两个背面矩形包含一个红色椭圆应该显示图像。仅当图片框大小模式为缩放时才会出现此问题。正如我所尝试的那样,只有在我每次设置新图像时调用 Application.DoEvent() 或调用 PictureBox.Update()/Refresh() 时,这些图片框才能重绘。

附图中的两个红色椭圆应该显示图像

private void DrawFrame(VideoBuffer videoBuffer, PlaybackStatistics statistics)
{
    Bitmap bmp = img as Bitmap;
    BitmapData bd = null;
    try
    {
        bd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);//bgra32

        using (var md = videoBuffer.Lock())
        {

            CopyMemory(bd.Scan0, md.value.scan0Ptr, videoBuff.stride * videoBuff.height);

            //bitmap.WritePixels(
            //    new Int32Rect(0, 0, videoBuffer.width, videoBuffer.height),
            //    md.value.scan0Ptr, videoBuffer.size, videoBuffer.stride,
            //    0, 0
            //);
        }

    }
    catch (Exception err)
    {
        //errBox.Text = err.Message;
        Debug.Print("DrawFrame:: " + err.Message);
    }
    finally
    {
        bmp.UnlockBits(bd);
    }
    imageBox.Image = bmp;
    /*Application.DoEvent() // not recommended since this method causes the current thread to be suspended
    or call imageBox.Update() // causes hanging on UI thread
    or imageBox.Refresh() // causes hanging on UI thread
    or PictureBox.Invalidate(), do nothing.*/
}

我创建图片框并按照此代码添加到面板中。

PictureBox ptBox = new PictureBox();
ptBox.Size = new Size(elementWidth, elementHeight);
ptBox.Name = "PictureBox_" + (j) + (i);
ptBox.Location = new Point(j * elementWidth, i * elementHeight); //relative location
ptBox.BorderStyle = BorderStyle.FixedSingle;
ptBox.SizeMode = PictureBoxSizeMode.Zoom;
mPanel.Controls.Add(ptBox);

一周后,我发现PictureBoxs发生错误并没有触发OnPaint(PaintEventArgs e)事件。这会导致新图像未重绘的错误。

标签: c#pictureboxonvif

解决方案


推荐阅读