突出显示位图的一部分

时间:2014-03-04 01:55:35

标签: c# bitmap

如何突出显示鼠标选择的位图的特定部分?突出显示的部分将以不同的颜色显示。有人可以帮忙吗?非常感谢。

The highlight specific part of bitmap are something like the picture shown

2 个答案:

答案 0 :(得分:1)

关于在图像或控件上“突出显示”的主要问题是您需要访问图形对象。要获得一个位图,您可以这样做:

g = Graphics.FromImage(myBitmap);
g.DrawRectangle(Pens.Red, 0, 0, 100, 100);
g.Dispose();

以下是一些使用相同原理但带有图片框控件的代码,以便在C#中使用鼠标移动。

private bool expanding;
private bool selectActive = false;
private Point selectStart;
private Point selectPosition;
private bool selecting;
private bool selectionExists;
private bool manualFinding;


private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (!selectActive)
    {
        return;
    }
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        selectStart = e.Location;
        selecting = true;
    }

}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (selecting)
    {
        selectPosition = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    int x = Math.Min(selectStart.X, selectPosition.X);
    int y = Math.Min(selectStart.Y, selectPosition.Y);
    int w = Math.Abs(selectStart.X - selectPosition.X);
    int h = Math.Abs(selectStart.Y - selectPosition.Y);
    if (selectionExists || selecting)
    {
        e.Graphics.DrawRectangle(Pens.Red, x, y, w, h);
    }

}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (!selecting)
    {
        return;

    }

    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        selecting = false;
        selectionExists = true;
    }

}

下面是一个不同的示例,说明如何创建可以绘制图像的控件,然后在每次调用paint事件期间可以在图像顶部绘制任意内容:

public class ImageControl : Control
{
    [Description("The base image for this control to render.")]
    public Bitmap Image { get; set; }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        // base.OnPaintBackground(pevent);
    }

    /// <summary>
    /// Override paint so that it uses your glow regardless of when it is instructed to draw
    /// </summary>
    /// <param name="pevent"></param>
    protected override void OnPaint(PaintEventArgs pevent)
    {
        pevent.Graphics.DrawImage(Image, 0, 0, Width, Height);
        pevent.Graphics.DrawLine(Pens.Blue, 0, 0, 100, 100);
    }

}

答案 1 :(得分:0)

补充特德的回答,这是我的两分钱。

如果要突出显示位图内的某些区域,我会绘制一个半透明的矩形。您可以使用alpha通道创建具有RGB颜色的SolidBrush()

    using (Graphics graphics = Graphics.FromImage(waveBitmap))
    {
        // Paint transparent black mask
        graphics.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 0, 0)), 0, 0, 100, 100);
    }

因此,使用此代码Color.FromArgb(100, 0, 0, 0),您将创建一个黑色(RGB 0,0,0),其alpha值(透明度)为100(值从0到255,其中0表示完全透明,而255是不透明的。