Могу ли я рисовать фигуры, такие как круг, прямоугольник, линия и т.д. Вне метода drawRect

Могу ли я рисовать фигуры, такие как круг, прямоугольник, линия и т.д. вне метода 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));

Ответ 1

В принципе вам нужен контекст для рисования чего-то. Вы можете считать контекст как белую бумагу. UIGraphicsGetCurrentContext вернет null, если вы не находитесь в допустимом контексте. В drawRect вы получаете контекст представления.

Сказав это, вы можете сделать внешний метод drawRect. Вы можете начать 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;
} 

Ответ 2

Для 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;
}