Swift

来源:互联网 发布:应用更新软件 编辑:程序博客网 时间:2024/05/16 14:34

项目需求,文字要有描边效果,在这里记录下来。 核心是使用NSAttributedString进行绘制。 建议将此方法写在扩展中。另外还看到一些博主写的描边效果,其方式是继承UILabel,然后重载drawTextInRect方法,我改成了Swift,在下面也一并附上,有兴趣的可以看看

 overridefunc viewDidLoad() {     super.viewDidLoad()             let lab =UILabel(frame:view.bounds)     lab.attributedText =drawOutlineAttributedString(string:"哎呦,不错哦", fontFloat:30, alignment: .center, textColor:UIColor.white, widthColor:UIColor.red)      view.addSubview(lab)    } func drawOutlineAttributedString(string:String? =nil, fontFloat:CGFloat,                                  alignment: NSTextAlignment, textColor:UIColor,                                  widthColor: UIColor) ->NSAttributedString {              let paragraph =NSMutableParagraphStyle()      paragraph.alignment = alignment              let dic = [NSFontAttributeName:UIFont.systemFont(ofSize: fontFloat),                 NSParagraphStyleAttributeName: paragraph,                 NSForegroundColorAttributeName: textColor,                 NSStrokeWidthAttributeName: (-1.5),                 NSStrokeColorAttributeName: widthColor]as [String :Any]              var attributedText:NSMutableAttributedString!      if string !=nil{          attributedText = NSMutableAttributedString.init(string: string!, attributes: dic)      } else {          attributedText = NSMutableAttributedString.init(string:"", attributes: dic)      }      return attributedText } 

重载drawTextInRect方法

    overridefunc drawText(in rect: CGRect) {        let shadowOffset =self.shadowOffset        let textColor =self.textColor                let c =UIGraphicsGetCurrentContext()        c!.setLineWidth(1)        c!.setLineJoin(.round)        c!.setTextDrawingMode(.stroke)        self.textColor =UIColor.white        super.drawText(in: rect)                c!.setTextDrawingMode(.fill)        self.textColor = textColor        self.shadowOffset =CGSize(width: CGFloat(0), height:CGFloat(0))        super.drawText(in: rect)        self.shadowOffset = shadowOffset    }

效果如下:

 



原创粉丝点击