Create new UIImage by adding shadow to existing UIImage

后端 未结 8 878
半阙折子戏
半阙折子戏 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:01

    Whilst trying to use some of the other examples here, I noticed that they seem to either hard-code the offset & blur, or do not correctly take them into account when sizing and positioning the output.

    The following code solves these issues (it's based on the original work by 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
        }
    }
    

提交回复
热议问题