我可以使用
在drawRect
方法之外绘制圆形,矩形,直线等形状
CGContextRef contextRef = UIGraphicsGetCurrentContext();
或仅在drawRect
内使用它是必须的。
请帮助我,让我知道如何在drawRect
方法之外绘制形状。
实际上我想继续在touchesMoved
事件上绘制点。
这是我绘制点的代码。
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(contextRef, 0, 255, 0, 1);
CGContextFillEllipseInRect(contextRef, CGRectMake(theMovedPoint.x, theMovedPoint.y, 8, 8));
答案 0 :(得分:15)
基本上你需要一个上下文来绘制一些东西。您可以将上下文视为白皮书。如果您不在有效的上下文中,UIGraphicsGetCurrentContext
将返回null
。在drawRect
中,您将获得该视图的上下文。
话虽如此,您可以在drawRect
方法之外绘制。您可以开始使用imageContext绘制内容并将其添加到视图中。
请看以下从here
获取的示例 - (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
// begin a graphics context of sufficient size
UIGraphicsBeginImageContext(image.size);
// draw original image into the context
[image drawAtPoint:CGPointZero];
// get the context for CoreGraphics
CGContextRef ctx = UIGraphicsGetCurrentContext();
// set stroking color and draw circle
[[UIColor redColor] setStroke];
// make circle rect 5 px from border
CGRect circleRect = CGRectMake(0, 0,
image.size.width,
image.size.height);
circleRect = CGRectInset(circleRect, 5, 5);
// draw circle
CGContextStrokeEllipseInRect(ctx, circleRect);
// make image out of bitmap context
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
// free the context
UIGraphicsEndImageContext();
return retImage;
}
答案 1 :(得分:1)
Swift 4
func imageByDrawingCircle(on image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: image.size.width, height: image.size.height), false, 0.0)
// draw original image into the context
image.draw(at: CGPoint.zero)
// get the context for CoreGraphics
let ctx = UIGraphicsGetCurrentContext()!
// set stroking color and draw circle
ctx.setStrokeColor(UIColor.red.cgColor)
// make circle rect 5 px from border
var circleRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
circleRect = circleRect.insetBy(dx: 5, dy: 5)
// draw circle
ctx.strokeEllipse(in: circleRect)
// make image out of bitmap context
let retImage = UIGraphicsGetImageFromCurrentImageContext()!
// free the context
UIGraphicsEndImageContext()
return retImage;
}