通过向现有UIImage添加阴影来创建新的UIImage

时间:2010-05-29 20:10:54

标签: iphone objective-c cocoa-touch uiimage cgcontext

我已经看过这个问题:UIImage Shadow Trouble

但接受的答案对我不起作用。

我正在尝试做的是获取UIImage并为其添加阴影,然后返回一个全新的UIImage,阴影和所有。

这就是我正在尝试的:

- (UIImage*)imageWithShadow {

    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef shadowContext = CGBitmapContextCreate(NULL, self.size.width, self.size.height + 1, CGImageGetBitsPerComponent(self.CGImage), 0, 
                                                 colourSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    CGContextSetShadow(shadowContext, CGSizeMake(0, -1), 1);
    CGContextDrawImage(shadowContext, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage);

    CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
    CGContextRelease(shadowContext);

    UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
    CGImageRelease(shadowedCGImage);

    return shadowedImage;
}

结果是我得到了与之前通过此方法完全相同的图像。

我这样做是正确的,或者是否有一些我不知道的东西?

8 个答案:

答案 0 :(得分:16)

您的代码存在一些问题:

  • 目标图像太小。确保有足够的地方画阴影。
  • 考虑使用CGContextSetShadowWithColor来定义阴影及其颜色。
  • 不要忘记坐标系被翻转,因此原点是左下角,而不是左上角。

通过解决这些问题,应该绘制阴影。

- (UIImage*)imageWithShadow {
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef shadowContext = CGBitmapContextCreate(NULL, self.size.width + 10, self.size.height + 10, CGImageGetBitsPerComponent(self.CGImage), 0, 
                                             colourSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    CGContextSetShadowWithColor(shadowContext, CGSizeMake(5, -5), 5, [UIColor blackColor].CGColor);
    CGContextDrawImage(shadowContext, CGRectMake(0, 10, self.size.width, self.size.height), self.CGImage);

    CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
    CGContextRelease(shadowContext);

    UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
    CGImageRelease(shadowedCGImage);

    return shadowedImage;
}

答案 1 :(得分:7)

iOS8 / Swift版本(作为UIImage的扩展):

extension UIImage {

    func addShadow(blurSize: CGFloat = 6.0) -> UIImage {

        let shadowColor = UIColor(white:0.0, alpha:0.8).cgColor

        let context = CGContext(data: nil,
                                width: Int(self.size.width + blurSize),
                                height: Int(self.size.height + blurSize),
                                bitsPerComponent: self.cgImage!.bitsPerComponent,
                                bytesPerRow: 0,
                                space: CGColorSpaceCreateDeviceRGB(),
                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

        context.setShadow(offset: CGSize(width: blurSize/2,height: -blurSize/2),
                          blur: blurSize,
                          color: shadowColor)
        context.draw(self.cgImage!,
                     in: CGRect(x: 0, y: blurSize, width: self.size.width, height: self.size.height),
                     byTiling:false)

        return UIImage(cgImage: context.makeImage()!)
    }
}

(根据Laurent Etiemble的& capikaw答案转换而来)

编辑 2016/10/31:转换为Swift 3,删除所有不必要的东西

用法:

let sourceImage: UIImage(named: "some image")
let shadowImage = sourceImage.addShadow()

答案 2 :(得分:5)

我需要一个接受UIImage作为参数的方法,并返回带阴影的略大的UIImage。这里的帖子对我很有帮助,所以这是我的方法。 返回的图像每边都有一个居中的5px阴影。

+(UIImage*)imageWithShadowForImage:(UIImage *)initialImage {

CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef shadowContext = CGBitmapContextCreate(NULL, initialImage.size.width + 10, initialImage.size.height + 10, CGImageGetBitsPerComponent(initialImage.CGImage), 0, colourSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colourSpace);

CGContextSetShadowWithColor(shadowContext, CGSizeMake(0,0), 5, [UIColor blackColor].CGColor);
CGContextDrawImage(shadowContext, CGRectMake(5, 5, initialImage.size.width, initialImage.size.height), initialImage.CGImage);

CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
CGContextRelease(shadowContext);

UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
CGImageRelease(shadowedCGImage);

return shadowedImage;
}

答案 3 :(得分:4)

我的UIImages需要更大的阴影。这是我的答案变体,允许自定义阴影大小,没有偏移。

    - (UIImage*)imageWithShadow:(UIImage*)originalImage BlurSize:(float)blurSize {

    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef shadowContext = CGBitmapContextCreate(NULL, originalImage.size.width + (blurSize*2), originalImage.size.height + (blurSize*2), CGImageGetBitsPerComponent(originalImage.CGImage), 0, colourSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    CGContextSetShadowWithColor(shadowContext, CGSizeMake(0, 0), blurSize, [UIColor blackColor].CGColor);
    CGContextDrawImage(shadowContext, CGRectMake(blurSize, blurSize, originalImage.size.width, originalImage.size.height), originalImage.CGImage);

    CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
    CGContextRelease(shadowContext);

    UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
    CGImageRelease(shadowedCGImage);

    return shadowedImage;
}

使用它像:

UIImage *shadowedImage = [self imageWithShadow:myImage BlurSize:30.0f];

答案 4 :(得分:2)

我在图像上绘制阴影的方法。它具有自定义阴影参数,并以正确的大小和屏幕比例呈现图像。应该在UIImage扩展中实现。 (斯威夫特3)。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
list.sort(Comparator.comparing(shop -> LocalDateTime.parse(shop.getDate(), formatter)));

答案 5 :(得分:2)

在这里尝试使用其他一些示例时,我注意到它们似乎是对偏移和模糊进行硬编码,或者在调整输出大小和位置时未正确考虑它们。

以下代码解决了这些问题(基于Igor Kulagin的原始工作):

extension UIImage {
    /// Returns a new image with the specified shadow properties.
    /// This will increase the size of the image to fit the shadow and the original image.
    func withShadow(blur: CGFloat = 6, offset: CGSize = .zero, color: UIColor = UIColor(white: 0, alpha: 0.8)) -> UIImage {

        let shadowRect = CGRect(
            x: offset.width - blur,
            y: offset.height - blur,
            width: size.width + blur * 2,
            height: size.height + blur * 2
        )
        
        UIGraphicsBeginImageContextWithOptions(
            CGSize(
                width: max(shadowRect.maxX, size.width) - min(shadowRect.minX, 0),
                height: max(shadowRect.maxY, size.height) - min(shadowRect.minY, 0)
            ),
            false, 0
        )
        
        let context = UIGraphicsGetCurrentContext()!

        context.setShadow(
            offset: offset,
            blur: blur,
            color: color.cgColor
        )
        
        draw(
            in: CGRect(
                x: max(0, -shadowRect.origin.x),
                y: max(0, -shadowRect.origin.y),
                width: size.width,
                height: size.height
            )
        )
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext()
        return image
    }
}

答案 6 :(得分:0)

要像在这种情况下将图片设为CGImage,请尝试

self.shadowImage.CGImage

答案 7 :(得分:0)

GK100在Swift 2 / iOS9中的答案

func addShadow(blurSize: CGFloat = 6.0) -> UIImage {

    let data : UnsafeMutablePointer<Void> = nil
    let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()!
    let bitmapInfo : CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)

    let myColorValues:[CGFloat] = [0.0, 0.0, 0.0, 0.8]
    let myColor = CGColorCreate(colorSpace, myColorValues)

    let shadowContext : CGContextRef = CGBitmapContextCreate(data, Int(self.size.width + blurSize), Int(self.size.height + blurSize), CGImageGetBitsPerComponent(self.CGImage), 0, colorSpace, bitmapInfo.rawValue)!

    CGContextSetShadowWithColor(shadowContext, CGSize(width: blurSize/2,height: -blurSize/2),  blurSize, myColor)
    CGContextDrawImage(shadowContext, CGRect(x: 0, y: blurSize, width: self.size.width, height: self.size.height), self.CGImage)

    let shadowedCGImage : CGImageRef = CGBitmapContextCreateImage(shadowContext)!
    let shadowedImage : UIImage = UIImage(CGImage: shadowedCGImage)

    return shadowedImage
}