【问题标题】:iOS - Drawing pencil stroke for iPhone appiOS - 为 iPhone 应用程序绘制铅笔描边
【发布时间】:2016-04-15 06:40:33
【问题描述】:

我正在开发Drawing application,我需要实现类似于Apple notes apppencil effect

所以我将 UIView 子类化并编写以下代码。

CGPoint midPoint(CGPoint p1, CGPoint p2)
{
    return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}

@interface DrawingView () {
    CGPoint currentPoint;
    CGPoint previousPoint1;
    CGPoint previousPoint2;
    CGMutablePathRef path;
}

@end

@implementation DrawingView

- (id)init
{
    self = [super init];
    if (self != nil) {
        path = CGPathCreateMutable();
    }
    return self;
}

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

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

    previousPoint2 = previousPoint1;
    previousPoint1 = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];

    CGPoint mid1 = midPoint(previousPoint1, previousPoint2);
    CGPoint mid2 = midPoint(currentPoint, previousPoint1);
    CGMutablePathRef subpath = CGPathCreateMutable();
    CGPathMoveToPoint(subpath, NULL, mid1.x, mid1.y);
    CGPathAddQuadCurveToPoint(subpath, NULL, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);
    CGRect bounds = CGPathGetBoundingBox(subpath);

    CGPathAddPath(path, NULL, subpath);
    CGPathRelease(subpath);

   [self setNeedsDisplayInRect:bounds];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddPath(context, path);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, 5.0f);
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextSetAlpha(context, 1.0f);
    CGContextStrokePath(context);
}

这工作正常,它产生如下输出。

但我需要如下图所示的输出。类似于 Apple Notes 应用。

任何想法如何实现这一点。

【问题讨论】:

  • 有什么导致这个的吗?

标签: ios objective-c core-graphics


【解决方案1】:

下载铅笔纹理并将此图像设置为您的 CGContext 笔触颜色。

private var pencilTexture = UIColor(patternImage: UIImage(named: "pencil_texture")!)
ctx.setStrokeColor(pencilTexture.cgColor)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多