gpt4 book ai didi

objective-c - 如何检测可拖动线上的触摸(使用 drawRect 绘制)

转载 作者:太空狗 更新时间:2023-10-30 03:29:18 26 4
gpt4 key购买 nike

召集所有专家!我看过各种帖子,老实说,我的需求与 SO 上提供的答案略有不同。

我想创建一个 UI,用户可以在其中在特定区域(我们现在称之为“ Canvas ”)上创建各种线条(直线、曲线、摆动等)。每行可以有多个实例。然后,用户可以根据需要拖动和编辑这些线。因此,他们可以拉伸(stretch)它、更改起点、终点等,甚至可以将整条线拖到 Canvas 的边界内。

我已经设法绘制了线(使用 drawRect)并在每条线的末端显示了可拖动的 handle (参见引用图像),用户可以在边界内拖动端点(红色 Canvas 的矩形)以满足需要。

enter image description here

我面临的问题是如何点击以激活特定行的编辑。因此,默认情况下,拖动 handle 将不可见,用户可以点击该行以激活“编辑”模式,并显示 handle (再次点击取消选择)。因此,在上图中,我希望能够检测到黄色矩形中的触摸。请记住,UIView 边界是整个 Canvas 区域,以允许用户自由拖动,因此检测触摸显然很困难,因为也有透明区域,并且每行可以有多个实例。

到目前为止,这是我的线类代码(startHandle 和 endHandle 是两端的句柄):

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint startPoint = CGPointMake(self.startHandle.frame.origin.x + self.startHandle.frame.size.width/2, self.startHandle.frame.origin.y + self.startHandle.frame.size.height/2);

CGPoint endPoint = CGPointMake(self.endHandle.frame.origin.x + self.endHandle.frame.size.width/2, self.endHandle.frame.origin.y + self.endHandle.frame.size.height/2);

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];

if (CGRectContainsPoint(CGRectMake(startPoint.x, startPoint.y, endPoint.x - startPoint.x , endPoint.y - startPoint.y), touchLocation))
{
//this is the green rectangle! I want the yellow one :)
NSLog(@"TOUCHED IN HIT AREA");
}
}

- (void)drawRect:(CGRect)rect {
[super drawRect:rect];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.bounds);

CGPoint startPoint = CGPointMake(self.startHandle.frame.origin.x + self.startHandle.frame.size.width/2, self.startHandle.frame.origin.y + self.startHandle.frame.size.height/2);

CGPoint endPoint = CGPointMake(self.endHandle.frame.origin.x + self.endHandle.frame.size.width/2, self.endHandle.frame.origin.y + self.endHandle.frame.size.height/2);


CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 2.0f);
CGContextMoveToPoint(context, startPoint.x, startPoint.y ); //start at this point
CGContextAddLineToPoint(context, endPoint.x, endPoint.y); //draw to this point

self.arrow.angle = [self pointPairToBearingDegrees:startPoint secondPoint:endPoint];
self.arrow.center = endPoint;
[self.arrow setNeedsDisplay];
// and now draw the Path!
CGContextStrokePath(context);

}

到目前为止我尝试过的事情:

  1. 尝试检测在起点和终点之间绘制的矩形内的触摸,但这确实会返回我需要的矩形,因为如果线的角度为 45 度,它的面积会更大(见绿色矩形)
  2. 尝试在 drawRect 的顶部绘制另一条较粗的线,但徒劳无功,因为我必须使其透明,并且它与 View 的任何其他区域相同。还尝试检测颜色,但这条较粗的线又必须是透明的。

我非常感谢这方面的任何帮助。如果您能告诉我如何为曲线执行此操作,则可加分。非常感谢您通读。

最佳答案

您可以做一些数学运算。当触摸事件发生时,您要查看线上距离触摸事件最近的点是什么,以及该最近点距离触摸事件有多远。如果距离太远,您需要将触摸事件视为与该线无关。如果距离足够近,您会希望将其视为在线上最近的点。

幸运的是,hard work已经完成,但您需要稍微重构代码以返回最近的点,例如:

// Return point on line segment vw with minimum distance to point p
vec2 nearest_point(vec2 v, vec2 w, vec2 p) {

const float l2 = (v.x-w.x)*(v.x-w.x) + (v.y-w.y)*(v.y-w.y);
if (l2 == 0.0) return v; // v == w case

// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2

const float t = ((p.x-v.x)*(w.x-v.x) + (p.y-v.y)*(w.y-v.y)) / l2;

if (t < 0.0) return v; // Beyond the 'v' end of the segment
else if (t > 1.0) return w; // Beyond the 'w' end of the segment

vec2 projection;
projection.x = v.x + t * (w.x - v.x);
projection.y = v.y + t * (w.y - v.y);

return projection;
}

... and later in code used in the touch event handler ...

vec2 np = nearest_point(linePoint0, linePoint2, touchPoint);

// Compute the distance squared between the nearest point on
// the line segment and the touch point.
float distanceSquared = (np.x-touchPoint.x)*(np.x-touchPoint.x) + (np.y-touchPoint.y)*(np.y-touchPoint.y);

// How far the touch point can be from the line segment
float maxDistance = 10.0;

// This allows us to avoid using square root.
float maxDistanceSquared = maxDistance * maxDistance;

if (distanceSquared <= maxDistanceSquared) {
// The touch was on the line.
// We should treat np as the touch point.
} else {
// The touch point was not on the line.
// We should treat touchPoint as the touch point.
}

更新

这是其中大部分的工作概念验证,位于 jsfiddle here或嵌入下方(最好作为整页运行):

function nearest_point(v, w, p) {
var l2 = (v.x-w.x)*(v.x-w.x) + (v.y-w.y)*(v.y-w.y);
if (l2 === 0.0) return v;
var t = ((p.x-v.x)*(w.x-v.x) + (p.y-v.y)*(w.y-v.y)) / l2;
if (t < 0.0) return v;
else if (t > 1.0) return w;
var projection = {};
projection.x = v.x + t * (w.x - v.x);
projection.y = v.y + t * (w.y - v.y);
return projection;
}

var cvs = document.getElementsByTagName('canvas')[0];
var ctx = cvs.getContext('2d');
var width = cvs.width, height = cvs.height;

function LineSegment() {
this.x0 = this.y0 = this.x1 = this.y1 = 0.0;
}

LineSegment.prototype.Set = function(x0, y0, x1, y1) {
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
}

var numSegs = 6;
var lineSegs = [];
for (var i = 0; i < numSegs; i++) lineSegs.push(new LineSegment());

ctx.lineCap = ctx.lineJoin = 'round';

var mouseX = width / 2.0, mouseY = width / 2.0;
var mouseRadius = 10.0;

var lastTime = new Date();
var animTime = 0.0;
var animate = true;
function doFrame() {
// We record what time it is for animation purposes
var time = new Date();
var dt = (time - lastTime) / 1000; // deltaTime in seconds for animating
lastTime = time;
if (animate) animTime += dt;

// Here we create a list of animated line segments
for (var i = 0; i < numSegs; i++) {
lineSegs[i].Set(
width * i / numSegs,
Math.sin(4.0 * i / numSegs + animTime) * height / 4.0 + height / 2.0,
width * (i + 1.0) / numSegs,
Math.sin(4.0 * (i + 1.0) / numSegs + animTime) * height / 4.0 + height / 2.0
);
}

// Clear the background
ctx.fillStyle = '#cdf';
ctx.beginPath();
ctx.rect(0, 0, width, height);
ctx.fill();

// Compute the closest point on the curve.
var closestSeg = 0;
var closestDistSquared = 1e100;
var closestPoint = {};

for (var i = 0; i < numSegs; i++) {
var lineSeg = lineSegs[i];
var np = nearest_point(
{x: lineSeg.x0, y: lineSeg.y0},
{x: lineSeg.x1, y: lineSeg.y1},
{x: mouseX, y: mouseY}
);

ctx.fillStyle = (i & 1) === 0 ? 'rgba(0, 128, 255, 0.3)' : 'rgba(255, 0, 0, 0.3)';
ctx.beginPath();
ctx.arc(np.x, np.y, mouseRadius * 1.5, 0.0, 2.0 * Math.PI, false);
ctx.fill();

var distSquared = (np.x - mouseX) * (np.x - mouseX)
+ (np.y - mouseY) * (np.y - mouseY);
if (distSquared < closestDistSquared) {
closestSeg = i;
closestDistSquared = distSquared;
closestPoint = np;
}
}

// Draw the line segments
//ctx.strokeStyle = '#008';
ctx.lineWidth = 10.0;
for (var i = 0; i < numSegs; i++) {
if (i === closestSeg) {
ctx.strokeStyle = (i & 1) === 0 ? '#08F' : '#F00';
} else {
ctx.strokeStyle = (i & 1) === 0 ? '#036' : '#600';
}
ctx.beginPath();
var lineSeg = lineSegs[i];
ctx.moveTo(lineSeg.x0, lineSeg.y0);
ctx.lineTo(lineSeg.x1, lineSeg.y1);
ctx.stroke();
}

// Draw the closest point
ctx.fillStyle = '#0f0';
ctx.beginPath();
ctx.arc(closestPoint.x, closestPoint.y, mouseRadius, 0.0, 2.0 * Math.PI, false);
ctx.fill();

// Draw the mouse point
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.arc(mouseX, mouseY, mouseRadius, 0.0, 2.0 * Math.PI, false);
ctx.fill();

requestAnimationFrame(doFrame);
}

doFrame();

cvs.addEventListener('mousemove', function(evt) {
var x = evt.pageX - cvs.offsetLeft,
y = evt.pageY - cvs.offsetTop;
mouseX = x;
mouseY = y;
}, false);

cvs.addEventListener('click', function(evt) {
animate = !animate;
}, false);
Move mouse over canvas to control the red dot.<br/>
Click on canvas to start/stop animation.<br/>
Green is the closest point on the curve.<br/>
Light red/blue is the closest point on each segment.<br/>
<canvas width="400" height="400"/>

关于objective-c - 如何检测可拖动线上的触摸(使用 drawRect 绘制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32308379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com