ios - 我可以在 drawRect 方法之外绘制圆形、矩形、直线等形状吗

标签 ios ipad drawrect cgcontextref

我可以在 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/

相关文章:

iphone - 如果drawRect : is overridden,子类UIView显示黑色背景

ios - 使用 bezierPathWithOvalInRect 绘制时边框被剪裁

ios - QuickDialog QEntryElement 省略号和重叠问题

ios - 其他 iOS 模拟器下载到哪里?

ios - Xcode 12.2 : Debugger not working with breakpoints

ios - 代码 : why launchOptions in didFinishLaunchingWithOptions always nil?

ios - UIImageNamed -> 按大小类获取 Assets

ios 应用程序被拒绝,需要帮助确定问题

objective-c - 在核心图形中颠倒文本

javascript - React Native、Rx.Net 和 RxSwift : commonalities