与圆角落的色的文本背景

问题描述 投票:2回答:1

我目前正在使用Swift中的iOS应用程序,我需要实现附图中显示的文本效果。

我有一个标签,显示用户写的一些文字,我需要使文字背景角(不是标签背景)四舍五入。

有没有办法做到这一点?我会搜索网络和Stackoverflow,但没有运气。

谢谢。

What I need to achieve

swift text background cornerradius
1个回答
1
投票

以下是一些可以帮助您的代码。我得到的结果与你想要的非常相似。

class MyTextView: UITextView {

    let textViewPadding: CGFloat = 7.0

    override func draw(_ rect: CGRect) {
        self.layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, self.text.count)) { (rect, usedRect, textContainer, glyphRange, Bool) in

            let rect = CGRect(x: usedRect.origin.x, y: usedRect.origin.y + self.textViewPadding, width: usedRect.size.width, height: usedRect.size.height*1.2)
            let rectanglePath = UIBezierPath(roundedRect: rect, cornerRadius: 3)
            UIColor.red.setFill()
            rectanglePath.fill()
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.