Swift - 在阴影层切孔 [英] Swift - Cut hole in shadow layer
问题描述
我想在一个 UIView 和 iOS 的阴影层切一个洞"
I want to "cut a hole" in the shadow layer of a UIView an Swift3, iOS
我有一个容器 (UIView),它有 2 个孩子:
I have a container (UIView), that has 2 children:
- 一个 UIImageView
- 该图像顶部的一个 UIView(叠加层")
我想给叠加层一个阴影并切出该阴影的内部矩形,以在 ImageView 的边缘创建类似发光的效果
插入辉光至关重要,因为图像占用了屏幕宽度
到目前为止我的代码:
I want to give the overlay a shadow and cut out an inner rect of that shadow, to create a glow-like effect at the edges of the ImageView
It is crucial that the glow is inset, since the image is taking the screen width
My code so far:
let glowView = UIView(frame: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
glowView.layer.shadowPath = UIBezierPath(roundedRect: container.bounds, cornerRadius: 4.0).cgPath
glowView.layer.shouldRasterize = true
glowView.layer.rasterizationScale = UIScreen.main.scale
glowView.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
glowView.layer.shadowOpacity = 0.4
container.addSubview(imageView)
container.addSubview(glowView)
现在的结果如下所示:
现在我想剪掉较暗的内部部分,以便只保留边缘的阴影
知道如何实现这一目标吗?
Now I would like to cut out the darker inner part, so that just the shadow at the edges remains
Any idea how to achieve this?
推荐答案
幸运的是,今天(2020 年)很容易
现在很容易做到这一点:
Fortunately it's now very easy today (2020)
These days it's very easy to do this:
这里是整件事
import UIKit
class GlowBox: UIView {
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = .clear
layer.shadowOpacity = 1
layer.shadowColor = UIColor.red.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 3
let p = UIBezierPath(
roundedRect: bounds.insetBy(dx: 0, dy: 0),
cornerRadius: 4)
let hole = UIBezierPath(
roundedRect: bounds.insetBy(dx: 2, dy: 2),
cornerRadius: 3)
.reversing()
p.append(hole)
layer.shadowPath = p.cgPath
}
}
一个非常方便的提示:
当你添加(即 .append
)两个像这样的贝塞尔路径时......
A really handy tip:
When you add (that is .append
) two bezier paths like that...
第二个必须是正常"或正常".或反转".
The second one has to be either "normal" or "reversed".
注意接近末尾的代码行:
Notice the line of code near the end:
.reversing()
像大多数程序员一样,我永远不记得是否应该正常";或反转"在不同的情况下!!
Like most programmers, I can NEVER REMEMBER if it should be "normal" or "reversed" in different cases!!
简单的解决方案...
很简单,两个都试试!
只需使用和不使用 .reversing()
它会以一种或另一种方式工作!:)
It will work one way or the other! :)
这篇关于Swift - 在阴影层切孔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!