我可以在drawRect方法之外绘制圆形,矩形,直线等形状 [英] Can I draw shapes like circle,rectangle,line etc outside drawRect method

查看:158
本文介绍了我可以在drawRect方法之外绘制圆形,矩形,直线等形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用

CGContextRef contextRef = UIGraphicsGetCurrentContext();

或者必须在 drawRect 只。
请帮帮我,让我知道如何在 drawRect 方法之外绘制形状。
实际上我想继续在 touchesMoved 事件上绘制点。

or is it mandatory to use it inside drawRect only. Please help me, let me know how can I draw shapes outside drawRect method. Actually i want to go on plotting dots on touchesMoved event.

这是我的绘图代码一个点。

This is my code for drawing a dot.

CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(contextRef, 0, 255, 0, 1);
CGContextFillEllipseInRect(contextRef, CGRectMake(theMovedPoint.x, theMovedPoint.y, 8, 8));


推荐答案

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

Basically you need a context to draw something. You can assume context as a white paper. UIGraphicsGetCurrentContext will return null if you are not in a valid context.In drawRect you get the context of the view.

话虽如此,你可以在外面画画 drawRect 方法。你可以开始一个imageContext来绘制东西并将它添加到你的视图中。

Having said that, you can draw outside drawRect Method. You can begin an imageContext to draw things and add it to your view.

请看下面的例子取自这里

    - (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;
} 

这篇关于我可以在drawRect方法之外绘制圆形,矩形,直线等形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆