在任意宽度的两点之间绘制矩形 [英] Drawing rectangle between two points with arbitrary width

查看:22
本文介绍了在任意宽度的两点之间绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在触摸屏上滑动手指时,我试图在两个 (2D) 点之间画一条线.为此,我计划在上一次触摸更新的 X 和 Y 与最新触摸更新的 X 和 Y 之间的每次触摸更新上绘制一个矩形.当用户在屏幕上滑动手指时,这应该会创建一条连续的实线.但是,我也希望这条线具有任意宽度.我的问题是,我应该如何计算每个矩形(x1、y1、x2、y2)所需的坐标?

I'm trying to draw a line between two (2D) points when the user swipes their finger across a touch screen. To do this, I plan on drawing a rectangle on every touch update between the X and Y of the previous touch update and the X and Y of the latest touch update. This should create a continuous and solid line as the user swipes their finger across the screen. However, I would also like this line to have an arbitrary width. My question is, how should I go about calculating the coordinates I need for each rectangle (x1, y1, x2, y2)?

--

另外:如果有人有任何关于我如何将抗锯齿应用到这条线的信息,那将是一个巨大的帮助.

Also: if anyone has any information on how I could then go about applying anti-aliasing to this line it'd be a massive help.

推荐答案

计算起点和终点之间的向量

Calculate a vector between start and end points

V.X := Point2.X - Point1.X;
V.Y := Point2.Y - Point1.Y;

然后计算一个垂直于它的(只需交换 X 和 Y 坐标)

Then calculate a perpendicular to it (just swap X and Y coordinates)

P.X := V.Y; //Use separate variable otherwise you overwrite X coordinate here
P.Y := -V.X; //Flip the sign of either the X or Y (edit by adam.wulf)

标准化垂直

Length = sqrt(P.X * P.X + P.Y * P.Y); //Thats length of perpendicular
N.X = P.X / Length;
N.Y = P.Y / Length; //Now N is normalized perpendicular

通过添加归一化垂直并将其乘以所需宽度的一半来计算形成矩形的 4 个点

Calculate 4 points that form a rectangle by adding normalized perpendicular and multiplying it by half of the desired width

R1.X := Point1.X + N.X * Width / 2;
R1.Y := Point1.Y + N.Y * Width / 2;
R2.X := Point1.X - N.X * Width / 2;
R2.Y := Point1.Y - N.Y * Width / 2;
R3.X := Point2.X + N.X * Width / 2;
R3.Y := Point2.Y + N.Y * Width / 2;
R4.X := Point2.X - N.X * Width / 2;
R4.Y := Point2.Y - N.Y * Width / 2;

使用这 4 个点绘制矩形.

Draw rectangle using these 4 points.

图片如下:

回答评论:如果 X 和 Y 相同,则该线正好是对角线,垂直于对角线是对角线.归一化是一种使长度等于 1 的方法,这样在这个例子中你的线的宽度就不会依赖于垂线的长度(这里等于线的长度).

To answer the comments: If X and Y are the same then the line is exactly diagonal and perpendicular to a diagonal is a diagonal. Normalization is a method of making a length to equal to 1, so that the width of your line in this example will not depend on perpendiculars length (which is equal to lines length here).

这篇关于在任意宽度的两点之间绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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