C# 或 VB.NET 中图像上的可拖动文本或形状 [英] Draggable text or shapes on an image in C# or VB.NET

查看:31
本文介绍了C# 或 VB.NET 中图像上的可拖动文本或形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 或 VB.NET 创建一个 Winforms 应用程序,这将允许我将文本或形状放置在图片框内的现有图像之上,并可以使用鼠标拖动该文本或形状.例如,如果我想在图像上放置一个 90X90 的正方形,我会在宽度"文本框中输入 90,在高度"文本框中输入 90,然后单击图像,它将被绘制在现有图像的顶部.然后我可以通过将鼠标移动到我想要的位置来定位它.如果需要,可能还有其他步骤(例如单击启动该过程的插入矩形"按钮).我尝试了一些想法,例如调用一个例程,将图片框重置为其原始图像并在引发鼠标移动"事件时绘制形状,但这显然太慢了.这是否应该在图片框的绘制事件中完成,如果是这样,有人可以指出我如何做的正确方向吗?这是可能的,还是我把这个想法简单化了?

I'm trying to create a Winforms application using either C# or VB.NET that will allow me to place text or a shape on top of an existing image inside a picturebox and have that text or shape draggable with the mouse. For example, if I want to place a 90X90 square on the image, I would enter 90 in a 'width' textbox, 90 in a 'height' textbox and click on the image and it would be drawn on top of the existing image. Then I can position it by moving the mouse where I want it to be exactly. There could be other steps if required (like clicking a 'insert rectangle' button that starts the process). I've tried a few ideas like calling a routine that resets the picturebox to it's original image and draws the shape when the 'mouse move' event is raised, but that is obviously too slow. Should this be done in the paint event of the picturebox, and if so, could someone point me in the right direction of how to do it? Is this possible, or am I oversimplifying the idea?

预先感谢您的帮助.

推荐答案

下面是一个非常简单的示例,说明如何在父控件内绘制可拖动的矩形.

Below is a very naive example of how to paint a draggable rectangle inside a parent control.

public class Draggable : PictureBox
{
    Rectangle shapeBounds;
    bool isDragging;
    Point dragPoint;

    public Draggable()
    {
        InitializeComponent();
        shapeBounds = new Rectangle(10, 10, 30, 30);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        if (shapeBounds.Contains(e.Location))
        {
            isDragging = true;
            dragPoint = new Point(
                e.Location.X - shapeBounds.Location.X,
                e.Location.Y - shapeBounds.Location.Y);
        }
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        base.OnMouseUp(e);
        isDragging = false;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        if (isDragging)
        {
            Point p = new Point(
                e.Location.X - dragPoint.X,
                e.Location.Y - dragPoint.Y);
            shapeBounds = new Rectangle(p, shapeBounds.Size);
            Invalidate();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.FillRectangle(Brushes.Red, shapeBounds);
    }
}

这篇关于C# 或 VB.NET 中图像上的可拖动文本或形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆