如何使用Core Graphics绘制具有自定义样式的线?

时间:2011-06-28 19:50:21

标签: iphone ios core-graphics quartz-graphics

我正在使用Core Graphics绘制一条线。它真的很简单,很简单。

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 5.0f, 5.0f);
    CGContextAddLineToPoint(c, 300.0f, 600.0f);
    CGContextSetLineWidth(c, 25);
    CGContextSetLineCap(c, kCGLineCapRound);
    CGContextStrokePath(c);
}

这很有效。假设我们想要绘制自定义样式线。假设我们想模仿蜡笔的风格。而设计师递给你的蜡笔风格图像:http://imgur.com/a/N40ig

为了完成这个效果,我想我需要做这样的事情:

  1. 创建特殊颜色版本的crayonImage1-crayonImage4

  2. 每次添加一行到行时,您都会使用一个蜡笔画

  3. 每次画点时都会交替使用蜡笔画。

  4. 第1步是有道理的。我可以使用以下方法:

    - (UIImage *)image:(UIImage *)img withColor:(UIColor *)color {    
        // begin a new image context, to draw our colored image onto
        UIGraphicsBeginImageContext(img.size);
    
        // get a reference to that context we created
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // set the fill color
        [color setFill];
    
        // translate/flip the graphics context (for transforming from CG* coords to UI* coords
        CGContextTranslateCTM(context, 0, img.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        // set the blend mode to color burn, and the original image
        CGContextSetBlendMode(context, kCGBlendModeColorBurn);
        CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
        CGContextDrawImage(context, rect, img.CGImage);
    
        // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
        CGContextClipToMask(context, rect, img.CGImage);
        CGContextAddRect(context, rect);
        CGContextDrawPath(context,kCGPathFill);
    
        // generate a new UIImage from the graphics context we drew onto
        UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        //return the color-burned image
        return coloredImg;
    }
    

    我不确定如何完成第2步和第3步。在CoreGraphics中是否有用于将图像设置为线点的API?如果是这样,它是如何使用的?

    提前致谢,

    -David

1 个答案:

答案 0 :(得分:0)

从以下示例开始:http://www.ifans.com/forums/showthread.php?t=132024

但是对于画笔,不要画线。只需使用CGContextDrawImage绘制画笔图像。

基本上,您只需为每次触摸绘制一幅图像。