5

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));
4

2 回答 2

15

基本上你需要一个上下文来绘制一些东西。您可以将上下文假设为白皮书。如果您不在有效的上下文中,UIGraphicsGetCurrentContext将返回。您将获得视图的上下文。nulldrawRect

drawRect话虽如此,您可以在Method之外绘制。您可以开始一个 imageContext 来绘制事物并将其添加到您的视图中。

看看下面的例子,取自这里

    - (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;
} 
于 2013-05-29T12:11:36.280 回答
2

对于斯威夫特 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;
}
于 2017-09-19T16:15:43.750 回答