我可以在 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));
最佳答案
基本上你需要一个上下文来绘制一些东西。您可以将上下文假设为白皮书。如果您不在有效上下文中,UIGraphicsGetCurrentContext
将返回 null
。在 drawRect
中,您可以获得 View 的上下文。
话虽如此,你可以在 drawRect
方法之外绘制。您可以启动一个 imageContext 来绘制内容并将其添加到您的 View 中。
请看下面的示例,摘自 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;
}
关于ios - 我可以在 drawRect 方法之外绘制圆形、矩形、直线等形状吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813090/