使用 Core Graphics 制作类似画笔的纹理

Posted

技术标签:

【中文标题】使用 Core Graphics 制作类似画笔的纹理【英文标题】:Making a brush-like texture with Core Graphics 【发布时间】:2011-11-14 05:53:06 【问题描述】:

我正在制作一个绘画应用程序,但在制作画笔纹理时遇到了问题。 我正在使用 Core Graphics 在 touchesBegantouchesMoved 上画一条粗线和圆圈,我希望它具有更平滑的纹理,就像真正的画笔一样。这可以使用 Core Graphics 吗?

这是我的代码:

CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 35.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 
    redAmt, blueAmt, greenAmt, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(),
    endingPoint.x, endingPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),
    currentTouch.x, currentTouch.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
touchDraw.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

【问题讨论】:

不要一遍又一遍地调用 UIGraphicsGetCurrentContext()。调用一次并保留结果。 【参考方案1】:

我建议将 OpenGL 用于绘画应用程序。查看“GLPaint”示例。它正是您在 OpenGL 中寻找的功能。 (在 CG 的帮助下)。如果你只是想在屏幕上绘制,或者是位图表示,openGL 应该快得多。

如果你要坚持使用 CG,你应该创建一个 CGLayer,在图层中绘制你的画笔纹理,然后将图层反复绘制到你的图像所在的最终上下文中。

查看 CGLayerCreate、CGContextDrawLayerAtPoint 的文档。

您将需要一些代码,通过定期在该路径上查找点来采样您想要绘制的路径,然后在这些点处绘制您的画笔形状。据我所知,CG 中不存在这样的函数或方法,因此您必须自己编写代码。线条应该不难,但它涉及贝塞尔或三次路径的一些数学运算。

【讨论】:

为什么 CGContextDrawLayerAtPoint 比 CGContextDrawImage 快? @PsychoDad 根据文档:“Quartz 可以将 CGLayer 对象缓存到视频卡,使得将 CGLayer 绘制到目标位置比渲染从位图上下文构造的等效图像快得多。”【参考方案2】:

实现画笔工具的简单方法是使用图像并将其反复合成到绘图上下文中。

【讨论】:

怎么样?对不起,我是个菜鸟……我真的很想学这个。谢谢!【参考方案3】:
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
UIGraphicsBeginImageContext(imageView1.frame.size);
[imageView1.image drawInRect:CGRectMake(0, 0,imageView1.frame.size.width, imageView1.frame.size.height)];
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 10);
CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinRound);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 0, 0, 0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), point.x, point.y);
CGContextClearRect (UIGraphicsGetCurrentContext(), CGRectMake(point.x, point.y, 40, 40));
CGContextStrokePath(UIGraphicsGetCurrentContext());
imageView1.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

【讨论】:

以上是关于使用 Core Graphics 制作类似画笔的纹理的主要内容,如果未能解决你的问题,请参考以下文章

本周新学的 GUI绘图技术

Swift - 将 EPS 文件(或类似文件)转换为 Core Graphics 路径

绘图不可或缺的画笔Paint-使用篇

界面构建 - UIViews vs Images vs Core graphics vs PDF 子类

使用 Core Graphics 绘图在 Retina 显示屏上看起来很厚实

Java中的Graphics2D类基本使用教程