Create new UIImage by adding shadow to existing UIImage

后端 未结 8 846
半阙折子戏
半阙折子戏 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-08 23:59

    GK100's answer in Swift 2 / iOS9

    func addShadow(blurSize: CGFloat = 6.0) -> UIImage {
    
        let data : UnsafeMutablePointer = 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
    }
    

提交回复
热议问题