本文介绍了迅捷-在阴影层上切孔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iOS的Swift3 UIView的阴影层中挖一个洞"

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".

注意结尾处的代码行:

             .reversing()

像大多数程序员一样,我永远都不能记住,如果它应该是正常"的,或颠倒"在不同情况下!!

Like most programmers, I can NEVER REMEMBER if it should be "normal" or "reversed" in different cases!!

简单的解决方案...

The simple solution ...

非常简单,尝试两者!

只需在不使用.reversing()

它将以一种方式或另一种方式起作用! :)

It will work one way or the other! :)

这篇关于迅捷-在阴影层上切孔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 02:18