CGContext的Objective-C包装类?

有没有人为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本身的包装……更新:…在我编写了自己的概念验证包装后,我发现了Marcel Weiher的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:.

如果我继续使用这个类,我可能会添加更多的构造函数,也许还有一些块方法(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];

(这不是那么可怕,我猜……)

点赞