(Swift 5対応)UILabelの文字に縁取り(袋文字)をする2つの方法


どうも、肩と背中の日焼けが激しすぎて服を着ないまま禁断の在宅勤務を行なっているiOSエンジニアのkaです。

文字の表示を簡単にネイティブの機能だけを使ってテレビ番組のテロップ風にしたいということでやってみました。

NSAttributedStringを使う方法

swift.swift
let stroke:UIColor = UIColor.black
let foreground:UIColor = UIColor.white
let width:CGFloat = 3.0

let strokeTextAttributes = [
    .strokeColor : stroke,
    .foregroundColor : foreground,
    .strokeWidth : width,
    .font : UIFont.boldSystemFont(ofSize: 20.0)
    ] as [NSAttributedString.Key : Any]
let string = NSMutableAttributedString.init(string: "縁取り文字", attributes: strokeTextAttributes)
label.attributedText = string

CGContextを使う方法

UILabelのサブクラスを作ります

DecoreateLabel.swift
class DecorateLabel: UILabel {

    var strokeColor:UIColor = UIColor.white
    var strokeSize:CGFloat = 2.0

    override func drawText(in rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() { 
            let textColor = self.textColor

            context.setLineWidth(self.strokeSize)
            context.setLineJoin(CGLineJoin.round)
            context.setTextDrawingMode(.stroke)
            self.textColor = self.strokeColor
            super.drawText(in: rect)

            context.setTextDrawingMode(.fill)
            self.textColor = textColor
        }
        super.drawText(in: rect)
    }
}

swift.swift
let label = DecorateLabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
let stroke:UIColor = UIColor.black
let foreground:UIColor = UIColor.white
let width:CGFloat = 8.0
label.strokeColor = stroke
label.textColor = foreground
label.strokeSize = width
label.text = "縁取り文字"

補足

NSAttributedStringを使う方法だと文字の内側に縁取り
CGContextを使う方法だと文字の外側に縁取りをします
場面によって使い分けましょう!

参考:

storyboard で UILabel を袋文字にする
UILabelの文字に枠をつけ、袋文字(縁取り文字)を作る
UILabelをNSAttributedStringで文字装飾(Swift 4対応)

終わりです

Brewus,Inc.
株式会社ブリューアス
https://brewus.co.jp