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

9
召集所有专家!我看到了各种帖子,老实说,我的需求与SO上的答案有些不同。
我想创建一个UI,让用户在特定区域(暂称为“画布”)上创建各种线条(直线、曲线、折线等)。每种线条可以有多个实例。然后用户可以根据需要拖动和编辑这些线条。因此,他们可以拉伸它,改变起点、终点等,甚至将整条线条拖到画布范围内。
我已经成功绘制了线条(使用drawRect),并在每条线的末端显示了可拖动的手柄(见参考图像)。用户可以拖动末端点以适应画布的范围。

enter image description here

我面临的问题是如何轻触来激活特定行的编辑。因此,默认情况下,拖动手柄不可见,用户可以轻触该行以激活“编辑”模式,并显示手柄(再次轻触取消选择)。因此,在上图中,我希望能够检测到黄色矩形区域的触摸。请记住,UIView边界是整个画布区域,以允许用户自由拖动,因此检测触摸显然很困难,因为还有透明区域,并且每行可能有多个实例。
以下是我目前为止针对线类的代码(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中尝试在顶部绘制另一条粗线,但是徒劳无功,因为我必须使它透明,并且它与视图的任何其他区域相同。还尝试检测颜色,但是同样这条粗线必须是透明的。

我真的很感谢在这方面提供任何帮助。如果您能向我展示如何对曲线进行此操作,则加分。非常感谢您阅读。


我会从获取touchLocation点开始,然后计算它与起始点和结束点之间的距离。一旦距离变小,触摸点就在直线上了。 - Tim Edwards
@TimEdwards 逻辑上听起来不错,也许一些代码会有所帮助,另外在曲线上如何工作呢?非常感谢您的帮助。 - Gurtej Singh
我对iOS一窍不通,但我进行了快速搜索并找到了CGPath。它具有执行各种操作的能力,包括矩形、线条和曲线,并且还具有看似适当的CGPathContainsPoint。那个类对你不起作用吗? - Joseph
@Joseph,非常感谢你帮我解决问题。你的建议很好,我已经尝试过了。说实话,当我使用CGPath时,我遇到了一些性能问题。每次用户移动端点或起点时,我需要重新绘制线条,而在这种情况下,CGPath的表现并不是很好,或者可能我没有用对它。再次感谢你!祝一切顺利。 - Gurtej Singh
我不确定在这种情况下CGPathCGPathContainsPoint是否有用。根据文档:“如果一个点在路径被填充时在绘制区域内,那么该点就包含在路径中。”因此,对于由路径“包围”的点,它基本上返回true。如果你只有一条线段,即使它是弯曲的,它也可能不会包围任何东西。 - Matthew Burke
3个回答

4
你可以进行一些数学计算。当触摸事件发生时,你需要查找距离触摸事件最近的线上点以及该最近点与触摸事件之间的距离。如果距离太远,则需要将触摸事件视为不属于该线。如果足够接近,则需要将其视为在该线上最近的点处发生。
幸运的是,较难的工作已经完成了,但你需要稍微重构代码来返回最近的点,例如:
// 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进行查看,或者以下嵌入方式(最好以全屏模式运行):

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"/>


谢谢@Kaganar。我有些困难,无法轻松将其转换为Objective-C代码,这可能需要一段时间。如果您手头有它,请帮忙转换一下好吗?此逻辑对曲线如何处理呢? - Gurtej Singh
我必须道歉,我不熟悉Objective-C——尽管在这种情况下适用的语法似乎几乎相同。我怀疑更大的问题是如何将其集成到苹果的iOS环境中,而我恐怕不熟悉这个环境的结构。关于曲线,如果您可以将曲线表示为一系列线段,则需要在每个线段上运行此测试,并使用最接近触摸点的点。我不确定您的曲线界面或表示是什么样子,因此无法更具体地说明。 - Kaganar
@Gurtej,别担心--我相信在发放赏金之前还有一个宽限期。看起来是24小时的宽限期-->http://stackoverflow.com/help/bounty(在底部附近)。 - Kaganar
不幸的是,这仍然没有解决我的问题。要么我没有正确地将其转换为Obj-C,要么由于起点和终点始终是动态的,所以这可能不起作用。但是,我似乎找到了一个可能有所帮助的线程:https://dev59.com/OGnWa4cB1Zd3GeqP267b。由于你指引了我正确的方向,在奖励结束之前如果我没有收到更好的答案,我会授予你这份悬赏。非常感谢你的帮助。 - Gurtej Singh
@Gurtej,希望我能帮你更多关于iOS的问题,但是我已经更新了这个问题,并提供了一个实时的Javascript演示,以防对其他人有所帮助。 - Kaganar
显示剩余2条评论

1

您可以在touchesBegan中创建一个CGPath,其中包含线的起点和终点,然后使用CGPathContainsPoint()来判断触摸是否落在该线上。

编辑: 我不确定如何仅根据起点和终点创建曲线路径。

我认为需要一个模型。您需要在创建每条线时存储其信息(作为CGPath或其他内容),并在每个操作后更新它。然后使用该信息查找被触摸的线。

您是否放弃了使用CALayers的想法?这样可以提高性能,因为您只需要在每个操作中重新绘制一条线而不是整个图形。

附言:我不是专家,可能有更聪明的处理方法。


听起来很有趣,但是性能如何?每次触摸发生时都会绘制路径吗?请记住,这些线条可能会有许多这样的实例,性能在这里是一个关键因素。如果您能提供一些支持您答案的代码,并解释它在曲线线条的情况下如何工作,那将是非常好的。感谢您的帮助。 - Gurtej Singh
谢谢您的更新答案,@Aris。是的,每次发生变化时我只绘制一个实例。因此,在舞台上可能会有多个这个类的实例,用户可以拖动其中任何一个。问题在于选择点击区域。对于曲线来说,当然还需要一个贝塞尔曲线的第三个点。即使按照您的建议将信息存储在模型中,每次触摸发生时我仍然需要为所有实例绘制一个CGPath。这会非常占用性能。您有什么想法? - Gurtej Singh

1
如果在起点和终点之间有一条任意曲线,您需要通过一个点集来表示这条曲线,即一些表示曲线的点。这可以是屏幕上曲线的像素,或者是一些点,它们之间的曲线可以通过直线适当地插值得到。
为了确定用户是否足够接近曲线,您可以将轻击手势识别器附加到绘制曲线的视图中。当视图被轻击时,它会向您提供轻击的位置,请参见docs
使用此位置,您需要计算该点与曲线上所有点之间的距离。如果这些值的最小值足够小,则用户已经触摸到了曲线。
如果曲线仅由起点、终点和中间可能有一个控制点组成,则它是单个直线段或两个直线段。在这种情况下,问题是找到点和直线段之间的距离。
那么,也许 这里给出的答案(包括代码)会有所帮助。

虽然我理解逻辑并非常感谢您的帮助,但我正在寻找更多与代码相关的示例来帮助我。弯曲路径将具有最多3个点,起始点和结束点以及一个控制点来控制曲线的程度。再次感谢您。 - Gurtej Singh
感谢您更新答案,但是您的建议与@kaganar上面提出的基本相同,它没有显示Obj-C代码,但是它让我朝着正确的方向前进。我感谢您的支持。谢谢。 - Gurtej Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接