在CGContext中绘制透明的PNG显示为黑色

时间:2018-06-27 12:12:49

标签: ios objective-c core-graphics

我需要从2个现有图像中获取一个新图像。 (第二个图标应在第一个图标下方显示为徽标)。问题是,如果顶部(nevr尝试使用底部的nevr)具有透明背景,则显示为黑色。 这是代码:

+(UIImage *) addBottomOverlayWithImage:(UIImage*) fgImage
                             inImage:(UIImage*) bgImage {

    if(!bgImage) {
        return nil;
    }

    CGFloat minSize = MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    CGSize maxImageSize = CGSizeMake(minSize-140, minSize-140);
    CGSize imageSize = CGSizeMake(maxImageSize.width,
                                  maxImageSize.height+fgImage.size.height*2);// image size including art work and logo

    UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    [bgImage drawInRect:CGRectMake( 0, 0, maxImageSize.width, maxImageSize.height)];

    [[UIColor whiteColor] setFill];

    CGRect targetForFgImage = CGRectMake(0, imageSize.height-fgImage.size.height, imageSize.width, fgImage.size.height); // bottom part , where the logo will be added
    CGContextFillRect(context, targetForFgImage);

    CGFloat widthForFgImage = MIN(imageSize.width - 22.0, fgImage.size.width);
    CGFloat heightForFgImage = MIN(fgImage.size.height,widthForFgImage * 0.3);

    UIImage *imageToUse = [fgImage imageScaledToFitSize:CGSizeMake(widthForFgImage, heightForFgImage)]; // the logo size

    CGFloat xVal = 11.0;
    if (imageSize.width > widthForFgImage) {
        xVal = (imageSize.width -  widthForFgImage) / 2.0;
    }

    CGFloat yVal;
    if (targetForFgImage.size.height > heightForFgImage) {
        CGFloat diff = targetForFgImage.size.height - heightForFgImage;
        yVal = (imageSize.height - fgImage.size.height + (diff / 2.0));
    } else {
        yVal = imageSize.height - heightForFgImage;
    }

    [imageToUse drawInRect:CGRectMake(xVal, yVal, widthForFgImage, heightForFgImage)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

只要做

UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height)), NO, 1);

将其设置为否以获取更多信息,请检查developer document of apple