用自定义画笔绘制一条线

时间:2014-01-13 08:11:37

标签: ios path core-graphics brush

您如何使用自定义画笔绘制线条(或路径)?

这是我想要使用的画笔:

enter image description here

显然我已经尝试过这样做了:

CGContextRef context = UIGraphicsGetCurrentContext();
UIImage *img = [UIImage imageNamed:@"Path.png"];
UIColor *fillImg = [UIColor colorWithPatternImage:img];
CGContextSetStrokeColorWithColor(context, fillImg.CGColor);

但这样做会产生一个相当奇怪且无法使用的结果,好像背景充满了那个图像并显示我画的部分(就像下面的图像一样)。

enter image description here

我想要用刷子抚摸A点和B点之间的一条线,如下图所示: enter image description here

更新 我有一个派生自UIView的类,作为故事板的子视图添加。这是班级的内容:

@implementation lineView {
    CGPoint startPoint;
    CGPoint endPoint;
    BOOL gotStart;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setMultipleTouchEnabled:NO];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context) ;
    UIImage *img = [UIImage imageNamed:@"Path.png"];
    UIColor *fillImg = [UIColor colorWithPatternImage:img];
    CGContextSetStrokeColorWithColor(context, fillImg.CGColor);

    CGContextSetLineWidth(context, 22.0);
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    CGContextStrokePath(context);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    if (!gotStart) {
        startPoint = location;
        gotStart = TRUE;
    } else {
        gotStart = FALSE;
        endPoint = location;
        [self setNeedsDisplay];
    }
}

1 个答案:

答案 0 :(得分:0)