UIBezierPath路径形状Clickble and Draggable

ale*_*lex 1 iphone cocoa-touch core-graphics uikit ios

我在视图中有一个UIBezierPath.我想在点击形状时显示警告,但实际发生的情况是警报不仅在我单击形状时显示,而且在我单击视图中的任何位置时显示.

如何更改此代码,以便只有当我在彩色形状内部单击时,才会收到警报?另外,如何在屏幕上绘制可拖动的形状?

#import "draw2D.h"
@implementation draw2D

- (id)initWithFrame:(CGRect)frame {

self = [super initWithFrame:frame];
if (self) {
    // Initialization code.
}
return self;
}

- (void)drawRect:(CGRect)rect {
UIBezierPath*    aPath = [UIBezierPath bezierPath]; 

[aPath moveToPoint:CGPointMake(200.053,79.688)];    
[aPath addLineToPoint:CGPointMake(100.053,179.688)];
[aPath addLineToPoint:CGPointMake(304.412,280.125)];
[aPath addLineToPoint:CGPointMake(308.055,298.513)];
[aPath addLineToPoint:CGPointMake(200.053,79.688)];

[aPath closePath]; 

[[UIColor blackColor] setStroke]; 
[[UIColor redColor] setFill]; 

CGContextRef aRef = UIGraphicsGetCurrentContext(); 
CGContextTranslateCTM(aRef, 50, 50); 
aPath.lineWidth = 5; 
[aPath fill]; 
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Some message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil]; 
//After some time 
[alert show]; 
[alert release]; 
}

- (void)dealloc {
[super dealloc];
}

@end
Run Code Online (Sandbox Code Playgroud)

ugh*_*fhw 12

执行此操作的最佳方法是对bezier路径进行测试.这需要访问drawRect:方法之外的路径.由于您的路径始终相同,因此您可以使用静态变量轻松完成此操作.

//add this method to your class
- (UIBezierPath *)myPath {
    static UIBezierPath *path = nil;
    if(!path) {
        path = [[UIBezierPath bezierPath] retain];
        [path moveToPoint:CGPoingMake(200.053,79.688)];
        [path addLineToPoint:CGPointMake(100.053,179.688)];
        [path addLineToPoint:CGPointMake(304.412,280.125)];
        [path addLineToPoint:CGPointMake(308.055,298.513)];
        [path addLineToPoint:CGPointMake(200.053,79.688)];
        [path closePath];
        path.lineWidth = 5;
    }
    return path;
}

- (void)drawRect:(CGRect)rect {
    UIBezierPath*    aPath = [self myPath];

    [[UIColor blackColor] setStroke]; 
    [[UIColor redColor] setFill]; 

    CGContextRef aRef = UIGraphicsGetCurrentContext(); 
    CGContextTranslateCTM(aRef, 50, 50); 
    [aPath fill]; 
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(![[self myPath] containsPoint:[[touches anyObject] locationInView:self]]) return;

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Some message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil]; 
    //After some time 
    [alert show]; 
    [alert release]; 
}
Run Code Online (Sandbox Code Playgroud)

编辑自定义视图,该视图仅响应路径内的事件.

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    return [[self myPath] containsPoint:point];
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,您无需检查触摸是否在touchesBegan中的路径内,因为您不应该获得任何会使测试失败的事件.您可以通过将触摸移动的相同数量的帧原点更改来移动视图.