Domanda

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;
}
È stato utile?

Soluzione

Change creating context like this:

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

Altri suggerimenti

You can get Retina Image from current context using screen's scale.

Here is solution for Swift. Swift 3

func getImageFromContext() -> UIImage{

    UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
    self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    self.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image!
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top