ios 淡入标签文本的结尾

z0qdvdin  于 2023-02-14  发布在  iOS
关注(0)|答案(5)|浏览(100)

我有一个UILabel,我想淡化字符串的末尾,这会超出范围,什么是更好的解决方案呢?我应该计算标签的宽度,和字符串的宽度比较,如果字符串的宽度大于标签的宽度,我应该淡化最后两个字母?我应该怎么做呢?我希望这会很容易。请写下你的答案。谢谢!我喜欢用这个方法来计算宽度:

CGRect labelRect = [text
                    boundingRectWithSize:labelSize
                    options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:@{
                     NSFontAttributeName : [UIFont systemFontOfSize:14]
                    }
                    context:nil];
ne5o7dgx

ne5o7dgx1#

Swift 4.0示例:

let gradient = CAGradientLayer()

    gradient.frame      = titleLabel.bounds
    gradient.colors     = [UIColor.white.cgColor, UIColor.clear.cgColor]
    gradient.startPoint = CGPoint(x: 0.1, y: 0.0)
    gradient.endPoint   = CGPoint(x: 0.95, y: 0.0)

    label.lineBreakMode = .byClipping
    label.layer.mask = gradient

结果:

yvgpqqbh

yvgpqqbh2#

可以使用CAGradientLayer淡化一个线标注

CAGradientLayer *l = [CAGradientLayer layer];
l.frame = self.textLabel.bounds;
l.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
l.startPoint = CGPointMake(0.1f, 1.0f);
l.endPoint = CGPointMake(0.95f, 1.0f);
self.textLabel.layer.mask = l;

pgky5nke

pgky5nke3#

仅从layoutSubviews()方法起作用

override func layoutSubviews() {
    super.layoutSubviews()

    let maskLayer = CALayer()
    maskLayer.frame = label.bounds

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = label.bounds
    gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.7, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.95, y: 0.0)

    maskLayer.addSublayer(gradientLayer)
    label.layer.mask = maskLayer
}
6xfqseft

6xfqseft4#

2023.典型的大纲解决方案:

不考虑语言方向,它假设背景是白色的,等等。
请注意,您必须明确决定和设置淡入淡出的长度,当然,在整个应用程序中是恒定的,您不能使用“文本宽度的.1”。这里我们使用标签的高度,效果很好。

class FadeyLabel: UIILabel {
    
    lazy var fade: CAGradientLayer = {
        let g = CAGradientLayer()
        g.colors = [UIColor.white.withAlphaComponent(0).cgColor,
            UIColor.white.withAlphaComponent(1).cgColor]
        g.startPoint = CGPoint(x: 0, y: 0)
        g.endPoint = CGPoint(x: 1, y: 0)
        layer.addSublayer(g)
        return g
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        fade.frame = CGRect(
            origin: CGPoint(x: bounds.width - bounds.height, y: 0),
            size: CGSize(width: bounds.height, height: bounds.height))
    }
}
8dtrkrch

8dtrkrch5#

我已经找到了答案-我应该使用google中的GTMFadeTruncatingLabelTest类

相关问题