我是iOS API的这些部分的新手,这里有一些问题导致我脑海中无限循环
为什么..BeginImageContext有一个大小,但..GetCurrentContext没有大小?如果..GetCurrentContext没有大小,它在哪里绘制?有什么界限?
为什么他们必须有两个上下文,一个用于图像,一个用于一般图形?图像上下文不是图形上下文吗?分离的原因是什么(我想知道我不知道的事情)
答案 0 :(得分:33)
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);
}
在这种情况下,您不需要创建图形上下文。它是自动为您创建的,允许您在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];
我希望这有助于为您解决问题。此外,您应该使用UIGraphicsBeginImageContextWithOptions(大小,不透明,缩放)。有关使用图形上下文的自定义绘图的进一步说明,请参阅我的回答here
答案 1 :(得分:9)
你在这里有点困惑。
顾名思义UIGraphicsGetCurrentContext
抓取CURRENT上下文,因此它不需要大小,它会抓取现有上下文并将其返回给您。
那么什么时候有现有的上下文?总是?否。当屏幕渲染帧时,将创建上下文。此上下文在DrawRect:
函数中可用,该函数用于绘制视图。
通常,您的函数不会在DrawRect:中调用,因此它们实际上没有可用的上下文。这是您致电UIGraphicsBeginImageContext
。
当您这样做时,创建图像上下文,然后您可以使用UIGraphicsGetCurrentContext
获取所述上下文并使用它。因此,您必须记住以UIGraphicsEndImageContext
要进一步清理 - 如果您在DrawRect:
中修改上下文,您的更改将显示在屏幕上。在您自己的功能中,您的更改不会显示在任何位置。您必须通过UIGraphicsGetImageFromCurrentImageContext()
调用在上下文中提取图像。
希望这有帮助!