只是想补充一点,您不必在 UIView 的“drawRect:”方法中绘制它。你可以在任何你想要的地方绘制它,只要你在 UIGraphics 图像上下文中进行。当我不想创建 UIView 的子类时,我总是这样做。这是一个工作示例:
UIBezierPath *circle = [UIBezierPath
bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];
//you have to account for the x and y values of your UIBezierPath rect
//add the x to the width (75 + 200)
//add the y to the height (100 + 200)
UIGraphicsBeginImageContext(CGSizeMake(275, 300));
//this gets the graphic context
CGContextRef context = UIGraphicsGetCurrentContext();
//you can stroke and/or fill
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
[circle fill];
[circle stroke];
//now get the image from the context
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];
现在只需将 UIImageView 添加为子视图。
此外,您也可以将其用于其他绘图。同样,经过一些设置后,它就像 drawRect: 方法一样工作。
//this is an arbitrary size for example
CGSize aSize = CGSizeMake(50.f, 50.f);
//this can take any CGSize
//it works like the frame.size would in the drawRect: method
//in the way that it represents the context's size
UIGraphicsBeginImageContext(aSize);
//this gets the graphic context
CGContextRef context = UIGraphicsGetCurrentContext();
//you can do drawing just like you would in the drawRect: method
//I am drawing a square just for an example to show you that you can do any sort of drawing in here
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);
//you can stroke and/or fill
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
CGContextDrawPath(context, kCGPathFillStroke);
//now get the image from the context
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage];
编辑:我应该补充的一点是,对于任何这种现代绘画,你应该换掉
UIGraphicsBeginImageContext(size);
为
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
这将为 Retina 和非 Retina 显示器正确绘制图形。
仅供参考,UIGraphicsBeginImageContext(size) 等同于 UIGraphicsBeginImageContextWithOptions(size, FALSE, 1.f),这对于可能具有一定透明度的非视网膜显示器来说很好。
但是,如果您不需要透明度,则为 opaque 参数传入 TRUE 会更加优化。
最安全和推荐的绘图方式是传入[[UIScreen mainScreen]scale] 作为比例参数。
因此,对于上面的示例,您可以改用这个:
UIGraphicsBeginImageContextWithOptions(aSize, FALSE, [[UIScreen mainScreen] scale]);
欲了解更多信息,请查看Apple's docs。