UIGraphicsGetCurrentContext与UIGraphicsBeginImageContext/UIGraphicsEndImageContext

Nih*_*hat 20 core-graphics objective-c ios ios7

我是iOS API的这些部分的新手,这里有一些问题导致我脑海中无限循环

  1. 为什么..BeginImageContext有一个大小,但..GetCurrentContext没有大小?如果..GetCurrentContext没有大小,它在哪里绘制?有什么限制?

  2. 为什么他们必须有两个上下文,一个用于图像,一个用于一般图形?图像上下文不是图形上下文吗?分离的原因是什么(我想知道我不知道的)

dav*_*Mac 34

UIGraphicsGetCurrentContext()返回对当前图形上下文的引用.它没有创建一个.这一点很重要,因为如果您在该灯光中查看它,您会发现它不需要大小参数,因为当前上下文只是创建图形上下文的大小.

UIGraphicsBeginImageContext(aSize)用于在UIView drawRect:方法之外的UIKit级别创建图形上下文.

您可以在这里使用它们.

如果你有一个UIView的子类,你可以覆盖它的drawRect:方法,如下所示:

- (void)drawRect:(CGRect)rect
{
    //the graphics context was created for you by UIView
    //you can now perform your custom drawing below

    //this gets you the current graphic context
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //set the fill color to blue
    CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor);

    //fill your custom view with a blue rect
    CGContextFillRect(ctx, rect);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不需要创建图形上下文.它是自动为您创建的,允许您在drawRect:方法中执行自定义绘图.

现在,在另一种情况下,您可能希望在drawRect:方法之外执行一些自定义绘制.在这里你会用到UIGraphicsBeginImageContext(aSize)

你可以这样做:

UIBezierPath *circle = [UIBezierPath
                        bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)];  

UIGraphicsBeginImageContext(CGSizeMake(200, 200));

//this gets the graphic context
CGContextRef context = UIGraphicsGetCurrentContext();

//you can stroke and/or fill
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
[circle fill];
[circle stroke];

//now get the image from the context
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];
Run Code Online (Sandbox Code Playgroud)

我希望这有助于为您解决问题.此外,您应该使用UIGraphicsBeginImageContextWithOptions(大小,不透明,缩放).对于图形上下文的自定义绘制的进一步说明,请参阅我的答案在这里


Jac*_*ack 10

你在这里有点困惑.

顾名思义就是UIGraphicsGetCurrentContext抓住CURRENT上下文,因此它不需要大小,它会抓取现有的上下文并将其返回给您.

那么什么时候有现有的背景?总是?否.当屏幕渲染帧时,将创建上下文.此上下文在DrawRect:函数中可用,该函数用于绘制视图.

通常,您的函数不会在DrawRect:中调用,因此它们实际上没有可用的上下文.这是你打电话的时候UIGraphicsBeginImageContext.

当你这样做,你创建一个图像上下文,然后你可以抓住所述上下文UIGraphicsGetCurrentContext并使用它.因此,你必须记住结束它UIGraphicsEndImageContext

要进一步清理 - 如果您修改了上下文DrawRect:,您的更改将显示在屏幕上.在您自己的功能中,您的更改不会显示在任何位置.您必须通过UIGraphicsGetImageFromCurrentImageContext()调用在上下文中提取图像.

希望这可以帮助!