0

现在我正在使用 UIBezierPath 和moveToPoint/addLineToPoint在视图的drawRect. 这个相同的视图touchesMoved从 viewController 接收。它修改了我绘制多边形时使用的posxposy变量,如下所示:

[path addLineToPoint:CGPointMake([p.getx floatValue]+posx, [p.gety floatValue]+posy)]

不幸的是,性能很糟糕,每当我移动它时,多边形都会留下痕迹。

实现我想要做的事情的最佳方式是什么?

编辑:drawRect。polys是一个带有poly对象的 NSMutableArray。每个多边形是一个 x/y 点。

- (void)drawRect:(CGRect)rect{
UIBezierPath* path;
UIColor* fillColor;
path = [UIBezierPath bezierPath];
for (int i = 0; i < [polys count]; i++){
    poly *p = [polys objectAtIndex:i];
    if (i == 0){
        [path moveToPoint:CGPointMake([p.getx floatValue]+posx, [p.gety floatValue]+posy)];
    }else{
        [path addLineToPoint:CGPointMake([p.getx floatValue]+posx, [p.gety floatValue]+posy)];
        fillColor = [UIColor blueColor]; // plan to use a random color here
        }
    }
[path closePath];
[fillColor setFill];
[path fill];
}
4

1 回答 1

1

还没弄清楚你的问题。我的猜测是您想用用户的手指绘制多边形。我有这个完美运行的小班,它可能会有所帮助:

@implementation View {
    NSMutableArray* _points;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    self.backgroundColor = [UIColor whiteColor];

    _points = [NSMutableArray array];

    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // Clear old path
    [_points removeAllObjects];

    UITouch* touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];

    [_points addObject:[NSValue valueWithCGPoint:p]];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];

    [_points addObject:[NSValue valueWithCGPoint:p]];

    [self setNeedsDisplay];
}

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

    for (int i = 0; i < _points.count; i++){
        CGPoint p = [_points[i] CGPointValue];
        if (i == 0){
            [path moveToPoint:p];
        }
        else {
            [path addLineToPoint:p];
        }
    }

    [path closePath];

    UIColor* color = [UIColor blueColor];
    [color setFill];
    [path fill];
}

@end

只需在您的应用程序中的某处添加视图,也许将其设为全屏。

于 2013-06-24T01:16:21.457 回答