只为@dfd。
所以,我去看了Create new UIImage by adding shadow to existing UIImage。向下滚动了一下之后,我开始找到几个基于 Swift 的解决方案。出于好奇,我把它们扔进了游乐场,看看它们能做什么。
我选择了这个解决方案...
import UIKit
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
}
}
let sourceImage = UIImage(named: "LogoSmall.png")!
let shadowed = sourceImage.withShadow(blur: 6, color: .red)
但是等等,那不是阴影,而是轮廓!
? 显然我们现在需要牵手每个人......
将参数更改为 ...
let shadowed = sourceImage.withShadow(blur: 6, offset: CGSize(width: 5, height: 5), color: .red)
产生投影。我喜欢这个解决方案,因为它不做任何假设,并提供适当数量的参数来根据需要更改输出。
我非常喜欢这个解决方案,我将扩展复制到我的个人库中,不知道什么时候会派上用场。
记住,为了产生这种风格的图像,原始图像需要是透明的。
有点像……
请记住,iOS 已经存在了很长时间,ObjC 已经存在了更长的时间。您可能会遇到许多仅在 ObjC 中提供的解决方案,这意味着拥有至少阅读代码的技能/能力仍然很重要。如果幸运的话,社区的其他成员会产生合适的 Swift 变体,但这并不总是可能的。
我确定我不需要写一篇关于如何在 Playground 中包含图像的完整教程的程度,有 plenty of examples 关于那个?