6

我想用画笔绘制透明区域,但我的代码工作得不是很好。我想有人可以在这里帮助我。我的代码:

// Handles the start of a touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGRect bounds = [self bounds];
    UITouch *touch = [[event touchesForView:self] anyObject];

    if (![image isPointTransparent:[touch locationInView:self]]
       || ![image isPointTransparent:[touch previousLocationInView:self]]) 
    {
        return;
    }

firstTouch = YES;

    // Convert touch point from UIView referential to OpenGL one (upside-down flip)

location = [touch locationInView:self];
location.y = bounds.size.height - location.y;
}

// Handles the continuation of a touch.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
    CGRect bounds = [self bounds];
    UITouch *touch = [[event touchesForView:self] anyObject];

    if (![image isPointTransparent:[touch locationInView:self]] 
        || ![image isPointTransparent:[touch previousLocationInView:self]]) 
    {
        return;
    }

// Convert touch point from UIView referential to OpenGL one (upside-down flip)
if (firstTouch) 
    {
    firstTouch = NO;
        previousLocation = [touch previousLocationInView:self];
    previousLocation.y = bounds.size.height - previousLocation.y;
} 
    else 
    {
    location = [touch locationInView:self];
    location.y = bounds.size.height - location.y;
    previousLocation = [touch previousLocationInView:self];
    previousLocation.y = bounds.size.height - previousLocation.y;
}

// Render the stroke
[self renderLineFromPoint:previousLocation toPoint:location];
}

// Handles the end of a touch event when the touch is a tap.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGRect bounds = [self bounds];
    UITouch *touch = [[event touchesForView:self] anyObject];

    if (![image isPointTransparent:[touch locationInView:self]] || ![image isPointTransparent:[touch previousLocationInView:self]]) 
    {  
        return;
    }

    if (firstTouch) 
    {
       firstTouch = NO;
       previousLocation = [touch previousLocationInView:self];
       previousLocation.y = bounds.size.height - previousLocation.y;
       [self renderLineFromPoint:previousLocation toPoint:location];
}
}
4

1 回答 1

0

要知道的重要一点是,您应该drawRect:UIView. 因此renderLineFromPoint:toPoint:,您代码中的方法应该只是构建一个行数组并告诉视图每次重绘,如下所示:

- (void)renderLineFromPoint:(CGPoint)from toPoint:(CGPoint)to
{
  [lines addObject:[Line lineFrom:from to:to]];
  [self setNeedsDisplay];
}

这假设您有一个具有 2 个CGPoint属性的 Line 类。你drawRect:可能看起来像这样:

- (void)drawRect:(CGRect)rect
{
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetRGBStrokeColor(context, 0.0f, 0.0f, 0.0f, 1.0f);
  for (Line *line in lines) {
    CGContextMoveToPoint(context, line.from.x, line.from.y);
    CGContextAddLineToPoint(context, line.to.x, line.to.y);
    CGContextStrokePath(context);
  }
}

如果您这样做(没有 OpenGL),则无需翻转 y 轴。

唯一剩下的就是实现该isPointTransparent:方法。从您的代码中很难知道这应该如何工作。

于 2013-04-17T18:51:18.427 回答