【问题标题】:Can't create Retina images with CGContextDrawImage无法使用 CGContextDrawImage 创建 Retina 图像
【发布时间】:2012-06-26 09:21:00
【问题描述】:

我正在使用 CGContext 组合其他两个图像来创建图像。即使我有@2x 图像,我也无法成功创建视网膜图像。

这是我的代码。你能帮忙吗?

-(UIImage*)makePinImageWithImage:(UIImage*)icon {
UIImage * pin = [UIImage imageNamed:@"defaultPin.png"]; // I have the @2x one.
int w = pin.size.width;
int h = pin.size.height;

CGRect iconRect = CGRectMake(16, 47, 24, 26); // the frame where mix icon in pin

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 8 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

// Drawing pin in context
CGContextDrawImage(context, CGRectMake(0, 0, w, h), pin.CGImage);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

// Drawing icon in context
CGContextDrawImage(context, iconRect, icon.CGImage);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

// Getting back the final image
CGImageRef imageCG = CGBitmapContextCreateImage(context);

CGContextRelease(context);    
CGColorSpaceRelease(colorSpace);

UIImage * createdImage = [UIImage imageWithCGImage:imageCG];
CGImageRelease(imageCG);

return createdImage;
}

谢谢

【问题讨论】:

    标签: iphone cgcontext retina-display cgimage


    【解决方案1】:

    这段代码是在文本窗口中完成的,应该或多或少做你想做的事。

    (UIImage*)makePinImageWithImage:(UIImage*)icon // this code assumes this image is @2x if the device is
    {
        UIImage *pin = [UIImage imageNamed:@"defaultPin.png"]; // I have the @2x one.
        CGFloat w = rintf(pin.size.width);
        CGFloat h = rintf(pin.size.height);
    
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(w, h), YES, 0);   // 0 means let iOS deal with scale for you
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, h);
        CGContextConcatCTM(context, flipVertical);
    
        CGRect iconRect = CGRectMake(16, 47, 24, 26); // the frame where mix icon in pin
    
        // Drawing pin in context
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), [pin CGImage]); // CGImage is a method, not a property
        //CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);  // this does not do anything does it? You never do a FillRect...
    
        // Drawing icon in context
        CGContextDrawImage(context, iconRect, [icon CGImage]);
        //CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);  // this does not do anything does it? You never do a FillRect...
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;   // will be either normally sized or retina sized depending on environment
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多