簡體   English   中英

如何將手勢識別器添加到uibezierpath繪制的形狀中

[英]How to add a gesture recognizer to a shape drawn by uibezierpath

我正在UIView的子類中的drawRect函數中繪制一個圓

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();  
    CGContextSetLineWidth(contextRef, 2.0);
    CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
    CGRect circlePoint = (CGRectMake(self.bounds.size.width/3, self.bounds.size.height/2, 200.0, 200.0));

    CGContextFillEllipseInRect(contextRef, circlePoint);
}

我想在圓圈中添加一個手勢識別器,使其可以播放

UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
                                        action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

我想過將UIGestureRecognizer拖到大圓圈所在位置的視圖(在故事板中),但圓圈比UIGestureRecognizer小部件大得多。

如何組合代碼或將UIGestureRecognizer分配給視圖的區域,該區域與圓的大小和位置完全相同?

簡短的回答是,你做不到。 手勢識別器附加到視圖,而不是形狀或層。 您必須為每個形狀創建自定義視圖對象。 你當然可以這樣做。

我建議你做的是創建一個UIView的自定義子類來管理你的所有形狀。 (我將其稱為ShapesView)讓自定義ShapesView管理自定義形狀對象的數組。 將手勢識別器附加到ShapesView。 在響應手勢的代碼中,讓它進行自定義命中測試以確定敲擊哪個形狀,並移動形狀。

UIBezierPath包含一個containsPoint方法,如果您為每個形狀維護bezier路徑,則允許您進行命中測試。

我不確定如何使用drawRect以你的方式做到這一點,但我已經使用UIBezierPath做了類似的事情。 我將UIView子類化,並將此視圖作為我的控制器的主視圖。 這是該視圖中的代碼,

- (id)initWithCoder:(NSCoder *)aDecoder {

     if (self = [super initWithCoder:aDecoder]) {
         self.shape = [UIBezierPath bezierPathWithOvalInRect:(CGRectMake(self.bounds.size.width/3, self.bounds.size.height/3, 200.0, 200.0))];
        }
     return self;
}

-(void)drawRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [self.shape fill];
}

shape是.h文件中聲明的屬性。 在視圖控制器.m文件中,我添加了手勢識別器,並檢查觸摸是否在形狀內,

@interface ViewController ()
@property (strong,nonatomic) RDView *mainView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mainView = (RDView *)self.view;
    UITapGestureRecognizer *singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleFingerTap];
}

-(void)handleSingleTap:(UITapGestureRecognizer *) tapper {
    if ([self.mainView.shape containsPoint:[tapper locationInView:self.mainView]]) {
        NSLog(@"tapped");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM