繁体   English   中英

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

[英]How to draw graphics in iphone gesture?

在用户在 iPhone 上进行平移手势(即用户触摸并拖动手指)后,我有一个问题要绘制一条线或圆形指示器。 但是,UIGraphicsGetCurrentContext() 总是返回 nil,有人知道如何在 iPhone 上实现吗?

谢谢,克鲁

@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 -drawInRect:(CGRect)rect方法中调用[myCanvasView setNeedsDisplay]绘制这条轨迹。

像这样的东西:

- (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

我用自定义手势做到了这一点。 当手势设置手势 state(从触摸开始、移动或结束)时,手势动作回调会在视图中返回,并且视图调用“setNeedsDisplayInRect”,然后从drawRect进行绘图。

您的实现的问题是您无法从手势的跟踪方法中设置图形上下文。 当一个视图被标记为需要重绘(通过'setNeedsDisplay')时,这是为你完成的。

这样做的原因是视图的内容可以缓存在一个层中,这对于优化动画和合成非常重要。 因此,如果您需要在视图中绘图,请通过调用setNeedsDisplay并从您的drawRect方法进行绘图,使界面的 rest 与您的更改保持同步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM