有人为 CGContext 函数组创建了包装类吗?
我昨天创建了一个简单的 Gradient 类,它封装了 CGGradient 功能的一个子集,以简化内存管理。这非常简单。但是显然还有更多的 CGContext 操作,我不确定我是否想在那里重新发明轮子。
本质上我正在寻找的是...
@interface CGContext : NSObject
{
CGContextRef context;
}
+ (CGContext *) bitmapContextWithData:(void *)data
width:(size_t)width
height:(size_t)height
bitsPerComponent:(size_t)bitsPerComponent
bytesPerRow:(size_t)bytesPerRow
colorspace:(CGColorSpaceRef)colorspace
bitmapInfo:(CGBitmapInfo)bitmapInfo;
- (void) saveGState;
- (void) restoreGState;
- (void) setBlendMode:(CGBlendMode)mode;
- (void) addLineToPoint:(CGPoint)point;
- (void) addLineToPointX:(CGFloat)x pointY:(CGFloat)y;
- (void) drawImage:(CGImageRef)image rect:(CGRect)rect;
- (void) concatCTM:(CGAffineTransform)transform;
- (CGAffineTransform) getCTM;
@end
等等。
(我将 99% 的绘图绘制到屏幕外位图中,这就是为什么我在这种情况下关心内存管理。如果我总是绘制到当前 UI 图形上下文中,例如事件屏幕,那么我就不会找不到真正有用的包装类。)
最佳答案
UIBezierPath根据文档,类“是 Core Graphics 框架中与路径相关的功能的 Objective-C 包装器……[它]实际上只是 CGPathRef 数据类型和与该路径关联的绘图属性的包装器。 “"Drawing and Printing Guide for iOS"有这个类的描述和一些漂亮的图表。 (另请参见它的同类 NSBezierPath 和 CGPathRef。)
至于 CGContext 本身的包装器......更新:......在我编写了自己的概念验证包装器之后,我发现了 MPWDrawingContext作者:马塞尔·魏尔。它添加了一堆有用的方法,并且也支持链接!
我刚刚掀起了 Ruby script为 CGContext 生成一个名为 CGCanvas 的包装类:
- https://github.com/alexch/unsuck/blob/master/unsuck/CGCanvas.h
- https://github.com/alexch/unsuck/blob/master/unsuck/CGCanvas.m
- usage docs
目前还不是很有用,但是证明了这个概念。我喜欢能够看到参数名称,尽管 API 的功能仍然很笨重。
之前:
CGContextFillEllipseInRect(context, CGRectMake(30.0, 210.0, 60.0, 60.0));
CGContextAddArc(context, 150.0, 60.0, 30.0, 0.0, M_PI/2.0, false);
CGContextStrokePath(context);
CGContextAddArc(context, 150.0, 60.0, 30.0, 3.0*M_PI/2.0, M_PI, true);
CGContextStrokePath(context);
之后:
[canvas fillEllipseInRect:CGRectMake(30.0, 210.0, 60.0, 60.0)];
[canvas addArc_x:150.0 y:60.0 radius:30.0 startAngle:0.0 endAngle:M_PI/2.0 clockwise:false];
[canvas strokePath];
[canvas addArc_x:150.0 y:60.0 radius:30.0 startAngle:3.0*M_PI/2.0 endAngle:M_PI clockwise:true];
[canvas strokePath];
我做了一些技巧来使名称有意义...例如,具有多个参数的函数名称获取附加到基本名称的第一个参数的名称(除非它已经以它结尾)。我使用下划线而不是更像 Cocoa 的“with”来将基本名称与参数名称分开,例如moveToPoint_x:y:
而不是 moveToPointWithX:y:
或 moveToPoint:y:
。
如果我继续使用这个类,我可能会添加更多构造函数,也许还会添加一些 block 方法 (like this guy did),这样您就可以同时开始、构建和描边一条路径。还有很多名字可以更短,很多方法可以使用一些默认值。
也许还有方法链!要是 Objective-C 不那么疯狂就好了。它必须看起来像这样:
[[[[[[[[canvas
setRGBStrokeColor_red: 1.0 green: 1.0 blue: 1.0 alpha: 1.0]
setRGBFillColor_red:0.0 green:0.0 blue:1.0 alpha:1.0]
setLineWidth:2.0]
fillEllipseInRect:CGRectMake(30.0, 210.0, 60.0, 60.0)]
addArc_x:150.0 y:60.0 radius:30.0 startAngle:0.0 endAngle:M_PI/2.0 clockwise:false]
strokePath]
addArc_x:150.0 y:60.0 radius:30.0 startAngle:3.0*M_PI/2.0 endAngle:M_PI clockwise:true]
strokePath];
(这不是那么可怕的,我想......)
关于CGContext 的 Objective-C 包装类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842646/