简体   繁体   中英

How to change size of CGContextRef

How can I increase size of CGContextRef after its creation.

if(UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0);
}
else {
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
}
CGContextRef ctr = UIGraphicsGetCurrentContext();

Can i change size of ctr?

Try doing it without the if-else conditions. Create a CGContext using that last line of code only.

Here's a simple example

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetLineWidth(context, 2.0);
    CGContextMoveToPoint(context, 100,100);
    CGContextAddLineToPoint(context, 200, 200);
    CGContextStrokePath(context);
}

I had the same problem as yours. I developed a function to resize the CGContext :

void MPResizeContextWithNewSize(CGContextRef *c, CGSize s) {
    size_t bitsPerComponents = CGBitmapContextGetBitsPerComponent(*c);
    size_t numberOfComponents = CGBitmapContextGetBitsPerPixel(*c) / bitsPerComponents;
    CGContextRef newContext = CGBitmapContextCreate(NULL, s.width, s.height, bitsPerComponents, sizeof(UInt8)*s.width*numberOfComponents,
                                                    CGBitmapContextGetColorSpace(*c), CGBitmapContextGetBitmapInfo(*c));
    // Copying context content
    CGImageRef im = CGBitmapContextCreateImage(*c);
    CGContextDrawImage(newContext, CGRectMake(0, 0, CGBitmapContextGetWidth(*c), CGBitmapContextGetHeight(*c)), im);
    CGImageRelease(im);

    CGContextRelease(*c);
    *c = newContext;
}

I don't know if it works with the context provided by UIGraphicsBeginImageContext(...) function, but if you create manually your context with CGBitmapContextCreate , it will work.

Hopes that helps after the time since you asked...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM