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

image.png

image.png

image.png
所以需要自己實(shí)現(xiàn),采用的方法是重寫(xiě)textlayer的drawRect,label也一樣
思路是先畫(huà)一層帶描邊效果的文字
然后再在這層文字上面畫(huà)不帶描邊的文字,將沒(méi)描邊的文字壓在描邊文字上面,代碼如下
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)
}
但是實(shí)際效果是,第二次畫(huà)的效果是上下顛倒的,效果如下

圖片發(fā)自簡(jiǎn)書(shū)App
查了下是cgcontext的坐標(biāo)系與UIkIt的坐標(biāo)系是相反的,相當(dāng)于一個(gè)二維笛卡爾坐標(biāo)系的第一象限

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