Search code examples
iosobjective-ccore-graphics

CGContext scale to retina


I have this code that renders a custom slidebar handle with a dynamic text inside. The problem is that I cannot get it to scale to retina resolution. It draws right on all devices and has the right size, but the resolution is low on retina. How do I change this code to double the end image resolution?

-(UIImage *)addText:(UIImage *)img{
    int w = img.size.width;
    int h = img.size.height;



    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 0, colorSpace,kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);

    char* text= (char *)[[NSString stringWithFormat:@"$%d", (int)betSlider.value * 5] cStringUsingEncoding:NSASCIIStringEncoding];
    CGContextSetShouldAntialias(context, true);
    CGContextSelectFont(context, "TimesNewRomanPS-BoldMT",mainFrame.size.width/22, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetRGBFillColor(context,255,255,255, 1);
    CGContextShowTextAtPoint(context,(img.size.width-(strlen(text)*strlen(text)*(img.size.width/27)))/2.5,img.size.width/2.5,text, strlen(text));
    CGImageRef imgCombined = CGBitmapContextCreateImage(context);


    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    UIImage *retImage = [UIImage imageWithCGImage:imgCombined];
    CGImageRelease(imgCombined);

    return retImage;
}

Solution

  • Change creating context like this:

    CGFloat scale = [[UIScreen mainScreen] scale]
    CGContextRef context = CGBitmapContextCreate(NULL, w * scale, h * scale, 8, 0, colorSpace,kCGImageAlphaPremultipliedFirst);