設(shè)計提出文字描邊效果,但是富文本自帶的文字描邊效果,是向文字內(nèi)外同時描邊 效果

image.png

image.png

image.png
所以需要自己實現(xiàn),采用的方法是重寫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)
}
但是實際效果是,第二次畫的效果是上下顛倒的,效果如下

圖片發(fā)自簡書App
查了下是cgcontext的坐標系與UIkIt的坐標系是相反的,相當于一個二維笛卡爾坐標系的第一象限

7790818-61fc7b4c75fe00b6.png
所以將contex上下翻轉(zhuǎn)
super.draw(in: ctx)
ctx.scaleBy(x: 1, y: -1)
ctx.translateBy(x: 0, y: -self.gxHeight)
效果就對了,