如何在iPhone手势中绘制图形?

| 我有一个问题要在用户在iPhone上进行平移手势(即用户触摸并拖动手指)后绘制线条或圆圈指示器。但是,UIGraphicsGetCurrentContext()始终返回nil,有人知道如何在iPhone上实现吗? 谢谢, lu
@interface MyView : UIView <UIGestureRecognizerDelegate> {
CGPoint location;
PanIndicator *panIndicator;
}

@implementation MyView 
- (id)init {
    if (self = [super init]) {
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [panGesture setMaximumNumberOfTouches:1];
        [panGesture setDelegate:self];
        [self addGestureRecognizer:panGesture];
        [panGesture release];

        panIndicator = [[PanIndicator alloc] init];
        [self addSubview:panIndicator];
    }
    return self;
}

- (void)panAction:(UIPanGestureRecognizer *)gR {
    if ([gR state]==UIGestureRecognizerStateBegan) {
        location = [gR locationInView:self];
    } else if ([gR state]==UIGestureRecognizerStateEnded) {
    //  The following code in this block is useless due to context = nil
//      CGContextRef context = UIGraphicsGetCurrentContext();
//      CGContextAddRect(context, CGRectMake(30.0, 30.0, 60.0, 60.0));
//      CGContextStrokePath(context);
    } else if ([gR state]==UIGestureRecognizerStateChanged) {
    CGPoint location2 = [gR locationInView:self];
        panIndicator.frame = self.bounds;
        panIndicator.startPoint = location;
        panIndicator.endPoint = location2;
//      [panIndicator setNeedsDisplay];    //I don\'t know why PanIncicator:drawRect doesn\'t get called
        [panIndicator drawRect:CGRectMake(0, 0, 100, 100)]; //CGRectMake is useless
    }
}
    
已邀请:
        您应该在应用程序的数据部分中跟踪手指。在
-(void)panAction:(UIPanGestureRecognizer *)gR
中调用
[myCanvasView setNeedsDisplay]
,并在myCanvasView
-drawInRect:(CGRect)rect
方法中绘制此轨道。 像这样:
- (void)panAction:(UIPanGestureRecognizer *)gR 
{
    [myData addPoint:[gR locationInView:gR.view]];
    [myCanvasView setNeedsDisplay];
}

- (void)drawInRect:(CGRect)rect
{
    [self drawLinesFromData:myData];
}
PanIndicator的草案:
@interface PanIndicator : UIView {}
@property (nonatomic, assign) CGPoint startPoint;
@property (nonatomic, assign) CGPoint endPoint;
@end

@implementation PanIndicator
@synthesize startPoint = startPoint_;
@synthesize endPoint = endPoint_;

- (void)drawRect:(CGRect)aRect 
{
    [[UIColor redColor] setStroke];

    UIBezierPath *pathToDraw = [UIBezierPath bezierPath];
    [pathToDraw moveToPoint:self.startPoint];
    [pathToDraw addLineToPoint:self.endPoint];
    [pathToDraw stroke]
}

@end
    
        我用自定义手势来完成此操作。当手势设置手势状态(通过触摸开始,移动或结束)时,手势操作回调将在视图中再次出现,并且视图调用\“ setNeedsDisplayInRect \”,然后从
drawRect
开始绘制。 实现的问题在于,您无需从手势的跟踪方法中设置图形上下文。当视图标记为需要重绘时(通过\'setNeedsDisplay \'),可以为您完成此操作。 这样做的原因是可以将视图的内容缓存在一个图层中,这对于优化动画和合成非常重要。因此,如果需要绘制视图,请调用
setNeedsDisplay
并通过
drawRect
方法进行绘制,以使界面的其余部分与更改保持同步。     

要回复问题请先登录注册