Create new UIImage by adding shadow to existing UIImage

后端 未结 8 877
半阙折子戏
半阙折子戏 2020-12-08 23:15

I\'ve taken a look at this question: UIImage Shadow Trouble

But the accepted answer didn\'t work for me.

What I\'m trying to do is take a UIImage and add a s

8条回答
  •  余生分开走
    2020-12-09 00:04

    iOS8 / Swift version (made as an extension to 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()!)
        }
    }
    

    (converted from Laurent Etiemble's & capikaw answers)

    EDIT 2016/10/31: converted to Swift 3, and removed all unnecessary stuff

    Usage:

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

提交回复
热议问题