LoginSignup
4
0

More than 5 years have passed since last update.

UILabelのテキストに描画する

Posted at

UILabelのテキストの上にバツ印やマル印を書きたいと思ったときのメモです。

結論から言うとテキストのCGRectを取得してTextの表示領域に描画をする必要があります。

テキストのCGRectを取得textRect(forBounds:limitedToNumberOfLines:)メソッドで行います。
Textの表示領域に描画はsuper.drawText(in:)で行います。

バツ印を描画するサンプルコードは以下です。

class PathLabel: UILabel {
    override func draw(_ rect: CGRect) {
        // textのRectを取得する
        let textRect = self.textRect(forBounds: bounds, limitedToNumberOfLines: 1)
        // UIBezierPath のインスタンス生成
        let line = UIBezierPath()
        // 起点
        line.move(to: CGPoint(x: textRect.minX, y: textRect.minY))
        // 帰着点
        line.addLine(to: CGPoint(x: textRect.maxX, y: textRect.maxY))
        line.move(to: CGPoint(x: textRect.maxX, y: textRect.minY))
        line.addLine(to: CGPoint(x: textRect.minX, y: textRect.maxY))
        // ラインを結ぶ
        line.close()
        // 色の設定
        UIColor.red.setStroke()
        // ライン幅
        line.lineWidth = 4
        // 描画
        line.stroke()
        // Textに書き込み
        super.drawText(in: rect)
    }
}

キャプチャ

上のコードを実行するとこんな風に描画されます。

Simulator Screen Shot - iPhone 8 Plus - 2018-06-01 at 09.41.02.png

わかりやすいようにUILabelの背景を水色にしました。
1という文字列のみに赤いバツ印が描画されています。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0