屏蔽 UIView/UIImageView 以剪切透明文本

Masking UIView/UIImageView to cutout transparent text(屏蔽 UIView/UIImageView 以剪切透明文本)

本文介绍了屏蔽 UIView/UIImageView 以剪切透明文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何屏蔽 UIView 或 UIImageView 以便从中剪切文本?

How can I mask an UIView or UIImageView so that a text is cutout from it?

我用谷歌搜索了很多,似乎很多人都在苦苦挣扎.最烦人的是,我总是试图反转快照视图的 alpha 以获得结果.

I googled a lot and it seems that many people struggled the same. Most irritating I always tried to invert the alpha of a snapshotted view to get the result.

我想要的是这样的:

推荐答案

这是自定义掩码标签.

import UIKit
final class MaskLabel: UILabel {

// MARK: - IBInspectoable
@IBInspectable var cornerRadius: CGFloat {
    get { return self.layer.cornerRadius }
    set { self.layer.cornerRadius = newValue }
}

@IBInspectable var borderWidth: CGFloat {
    get { return self.layer.cornerRadius }
    set { self.layer.borderWidth = newValue }
}

@IBInspectable var borderColor: UIColor {
    get { return UIColor(cgColor: self.layer.borderColor ?? UIColor.clear.cgColor) }
    set { self.layer.borderColor = newValue.cgColor }
}

@IBInspectable var insetTop: CGFloat {
    get { return self.textInsets.top }
    set { self.textInsets.top = newValue }
}

@IBInspectable var insetLeft: CGFloat {
    get { return self.textInsets.left }
    set { self.textInsets.left = newValue }
}

@IBInspectable var insetBottom: CGFloat {
    get { return self.textInsets.bottom }
    set { self.textInsets.bottom = newValue }
}

@IBInspectable var insetRight: CGFloat {
    get { return self.textInsets.right }
    set { self.textInsets.right = newValue }
}



// MARK: - Value
// MARK: Public
private var textInsets = UIEdgeInsets.zero
private var originalBackgroundColor: UIColor? = nil



// MARK: - Initializer
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    setLabelUI()
}

override init(frame: CGRect) {
    super.init(frame: frame)

    setLabelUI()
}

override func prepareForInterfaceBuilder() {
    setLabelUI()
}


// MARK: - Draw
override func drawText(in rect: CGRect) {
    super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.saveGState()
    context.setBlendMode(.clear)

    originalBackgroundColor?.setFill()
    UIRectFill(rect)

    super.drawText(in: rect)
    context.restoreGState()
}


// MARK: - Function
// MARK: Private
private func setLabelUI() {
    // cache (Before masking the label, the background color must be clear. So we have to cache it)
    originalBackgroundColor = backgroundColor
    backgroundColor = .clear

    layer.cornerRadius = cornerRadius
    layer.borderWidth  = borderWidth
    layer.borderColor  = borderColor.cgColor
}
}

这就是结果.

这篇关于屏蔽 UIView/UIImageView 以剪切透明文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:屏蔽 UIView/UIImageView 以剪切透明文本

基础教程推荐