如何在UIBezierPath中填充颜色?

时间:2013-03-12 10:30:44

标签: ios uibezierpath

我在touchesMoved中通过UIBezierPath绘制一个形状。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    secondPoint = firstPoint;
    firstPoint = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];

    CGPoint mid1 = midPoint(firstPoint, secondPoint);
    CGPoint mid2 = midPoint(currentPoint, firstPoint);

    [bezierPath moveToPoint:mid1]; 
    [bezierPath addQuadCurveToPoint:mid2 controlPoint:firstPoint];

    [self setNeedsDisplay]; 
}

我想在closePath之后填充其中的RED颜色但不能。请帮忙!

- (void)drawRect:(CGRect)rect
{
    UIColor *fillColor = [UIColor redColor];
    [fillColor setFill];
    UIColor *strokeColor = [UIColor blueColor];
    [strokeColor setStroke];
    [bezierPath closePath];
    [bezierPath fill];
    [bezierPath stroke]; 
}

2 个答案:

答案 0 :(得分:18)

如果你有一个bezier路径存储在别处,这应该有效:

修改

查看您编辑的代码,发生的事情是,当您关闭正在绘制的路径时,您将获得一条线,而不是形状,因为您只有两点。

解决此问题的一种方法是在点移动时创建路径,但是笔划并填充该路径的副本。例如这是未经测试的代码,我直接在

中编写
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    secondPoint = firstPoint;
    firstPoint = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];

    CGPoint mid1 = midPoint(firstPoint, secondPoint);
    CGPoint mid2 = midPoint(currentPoint, firstPoint);

    [bezierPath moveToPoint:mid1]; 
    [bezierPath addQuadCurveToPoint:mid2 controlPoint:firstPoint];

    // pathToDraw is an UIBezierPath * declared in your class
    pathToDraw = [[UIBezierPath bezierPathWithCGPath:bezierPath.CGPath];

    [self setNeedsDisplay]; 
}

然后您的绘图代码可以:

- (void)drawRect:(CGRect)rect {
    UIColor *fillColor = [UIColor redColor];
    [fillColor setFill];
    UIColor *strokeColor = [UIColor blueColor];
    [strokeColor setStroke];

    // This closes the copy of your drawing path.
    [pathToDraw closePath];

    // Stroke the path after filling it so that you can see the outline
    [pathToDraw fill]; // this will fill a closed path
    [pathToDraw stroke]; // this will stroke the outline of the path.

}

有一些整理可以做touchesEnded,这可以提高性能,但你明白了。

答案 1 :(得分:-3)

你必须保留UIBezierPath的数组。试试这段代码,

 - (void)drawRect:(CGRect)rect
    {

        for(UIBezierPath *_path in pathArray){


         [_path fill];
        [_path stroke];
        }
    }

    #pragma mark - Touch Methods
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        myPath=[[UIBezierPath alloc]init];
        myPath.lineWidth = currentSliderValue;

        UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
        [myPath moveToPoint:[mytouch locationInView:self]];
        [pathArray addObject:myPath];
    }
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
        [myPath addLineToPoint:[mytouch locationInView:self]];
        [self setNeedsDisplay];

    }