书法绘图IOS Coregraphics

时间:2013-05-27 14:00:38

标签: ios objective-c cocoa-touch core-graphics

我希望有一些标记为红色的东西作为标记但不知道是否可以完成。

看起来像使用书法笔进行标记。

enter image description here

按照“Andrey”的说法尝试下面的代码,在绘图时我得到以下带有空格的输出。

enter image description here

刷子图像可在此处找到,使用的是enter image description here

对代码进行进一步更改后,我发现仍然无法获得预期的结果。 在这里,我试图填补当前点和下一点之间存在的路径。

- (void)drawRect:(CGRect)rect
{
    // Drawing code


    CGFloat w=5.0;
    CGFloat h=2.0;
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);

    for(int i=0;i<self.positions.count;i++){
        CGPoint point=[[self.positions objectAtIndex:i] CGPointValue];

        CGFloat x=point.x-(w/2.0);
        CGFloat y=point.y-(h/2.0);
        CGContextFillRect(context, CGRectMake(x, y, w, h));
        if(i+1<self.positions.count){
            CGPoint nextPoint=[[self.positions objectAtIndex:(i+1)] CGPointValue];
            CGMutablePathRef myPath=CGPathCreateMutable();
            CGPathMoveToPoint(myPath, NULL, x, y);
            CGFloat x1=nextPoint.x-(w/2.0);
            CGFloat y1=nextPoint.y-(h/2.0);

            CGPathAddLineToPoint(myPath, NULL, x1, y1);
            CGPathAddLineToPoint(myPath, NULL, w, y1);
            CGPathAddLineToPoint(myPath, NULL, w, y);
            CGPathCloseSubpath(myPath);
            CGContextFillPath(context);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

可以通过在UIView子类中使用覆盖的drawRect:消息绘制图像来完成这些图片。您还需要添加某种触摸处理程序来捕捉触摸。所以这里有一些代码:

@interface DrawingView ()

@property (nonatomic, strong) NSMutableArray *positions;

@end

@implementation DrawingView

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

- (void)awakeFromNib
{
    self.positions = [[NSMutableArray alloc] init];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    UIImage *brushImage = [UIImage imageNamed:@"brush.png"];
    for (NSValue *object in self.positions) {
        CGPoint point = [object CGPointValue];
        [brushImage drawAtPoint:CGPointMake(point.x - brushImage.size.width / 2.0, point.y - brushImage.size.height / 2.0)];
    }
}

- (void)addPoint:(CGPoint)point
{
    [self.positions addObject:[NSValue valueWithCGPoint:point]];

    [self setNeedsDisplay];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [self addPoint:[touch locationInView:self]];
}

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

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [self addPoint:[touch locationInView:self]];
}

@end

您只需要创建一个合适的brush.png并将这些视图放在任何您想要的位置。