8

I want to create a CGImageRef and draw points to it.

What context to use to create an empty CGImageRef and be able to draw onto it. CGContextRef or CGBitmapContextRef?

If you can provide code to create an empty CGImageRef image and draw to it I would appreciate.

Cyprian
  • 9,423
  • 4
  • 39
  • 73

1 Answers1

20
#define HIRESDEVICE (((int)rintf([[[UIScreen mainScreen] currentMode] size].width/[[UIScreen mainScreen] bounds].size.width )>1))


- (CGImageRef) blerg
    {
    CGFloat imageScale = (CGFloat)1.0;
    CGFloat width = (CGFloat)180.0;
    CGFloat height = (CGFloat)180.0;

    if ( HIRESDEVICE )
        {
        imageScale = (CGFloat)2.0;
        }

    // Create a bitmap graphics context of the given size
    //
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, width * imageScale, height * imageScale, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);


    // Draw ...
    //
    CGContextSetRGBFillColor(context, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)1.0 );
    // …


    // Get your image
    //
    CGImageRef cgImage = CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    return cgImage;
    }
John Carter
  • 2,056
  • 1
  • 17
  • 16
  • 2
    For some reason I always had a blank gray area when I tried this, no matter what I set the fill color values to. – micahhoover Oct 19 '11 at 01:29
  • 3
    I'd use 'UIGraphicsBeginImageContextWithOptions' on iOS4 or newer. That way no need to consider scale factor. – bioffe Dec 07 '11 at 21:36
  • 3
    It would be simpler and more future-proof to use the value from UIScreen.mainScreen.scale for imageScale, rather than a boolean 2 or 1. – Chris Hatton Apr 20 '13 at 13:19