美文网首页
ios 文字外描边效果

ios 文字外描边效果

作者: 卡卡罗忒 | 来源:发表于2020-01-08 18:13 被阅读0次

    设计提出文字描边效果,但是富文本自带的文字描边效果,是向文字内外同时描边 效果


    image.png
    image.png
    image.png

    所以需要自己实现,采用的方法是重写textlayer的drawRect,label也一样
    思路是先画一层带描边效果的文字
    然后再在这层文字上面画不带描边的文字,将没描边的文字压在描边文字上面,代码如下

    public override func draw(in ctx: CGContext) {
            guard let attr = self.string as? NSAttributedString else {
                super.draw(in: ctx)
                return
            }
            var newAtt = NSAttributedString.init(attributedString: attr)
            newAtt = newAtt.appendAddAttributes([NSAttributedString.Key.strokeColor : self.strokeColor.cgColor])
            newAtt = newAtt.appendAddAttributes([NSAttributedString.Key.foregroundColor : UIColor.red.cgColor])
            newAtt = newAtt.appendAddAttributes([NSAttributedString.Key.strokeWidth : 15])
            self.string = newAtt
            super.draw(in: ctx)
            self.string = attr
            super.draw(in: ctx)
        }
    

    但是实际效果是,第二次画的效果是上下颠倒的,效果如下


    ios 文字外描边效果

    查了下是cgcontext的坐标系与UIkIt的坐标系是相反的,相当于一个二维笛卡尔坐标系的第一象限


    7790818-61fc7b4c75fe00b6.png

    所以将contex上下翻转

            super.draw(in: ctx)
            ctx.scaleBy(x: 1, y: -1)
            ctx.translateBy(x: 0, y: -self.gxHeight)
    

    效果就对了,

    相关文章

      网友评论

          本文标题:ios 文字外描边效果

          本文链接:https://www.haomeiwen.com/subject/mpbsactx.html