只是想补充一下,您不必一定要在UIView的“drawRect:”方法中绘制它。只要您在UIGraphics图像上下文中进行绘制即可。当我不想创建UIView子类时,我经常这样做。以下是一个有效的示例:
UIBezierPath *circle = [UIBezierPath
bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];
UIGraphicsBeginImageContext(CGSizeMake(275, 300));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
[circle fill];
[circle stroke];
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];
现在将UIImageView添加为子视图。
此外,您还可以将其用于其他绘图。同样,在进行一些设置后,它的工作方式就像drawRect:方法一样。
CGSize aSize = CGSizeMake(50.f, 50.f);
UIGraphicsBeginImageContext(aSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 0.f, 0.f);
CGContextAddLineToPoint(context, aSize.width, 0.f);
CGContextAddLineToPoint(context, aSize.width, aSize.height);
CGContextAddLineToPoint(context, 0.f, aSize.height);
CGContextClosePath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
CGContextDrawPath(context, kCGPathFillStroke);
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage];
编辑:
我应该补充的一件事是,对于任何现代的绘图,你都应该更换。
UIGraphicsBeginImageContext(size);
for
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
这将正确地为Retina和非Retina显示器绘制您的图形。
FYI,
UIGraphicsBeginImageContext(size)
等同于
UIGraphicsBeginImageContextWithOptions(size, FALSE, 1.f)
,适用于可能具有一些透明度的非Retina显示器。
然而,如果您不需要透明度,则将TRUE传递给opaque参数更为优化。
最安全和推荐的绘制方式是将
[[UIScreen mainScreen]scale]
作为比例参数传递。
因此,对于上面的示例,您将使用以下内容:
UIGraphicsBeginImageContextWithOptions(aSize, FALSE, [[UIScreen mainScreen] scale]);
更多信息请查看
苹果文档。