LoginSignup
5
5

More than 5 years have passed since last update.

Swiftで文字列の輪郭に線をつける

Posted at

概要

Swiftで袋文字を実現したいという話を聞いて、調べたら実現方法がさっくり見つかったので残しておくことにした。
ブログから転記

実現方法

UILabelextension を定義して、そのメソッドを使うだけ。

参考記事のままだとエラーになるのでよしなに修正してある。

extension UILabel{

    /// makeOutLine
    ///
    /// - Parameters:
    ///   - strokeWidth: 線の太さ。負数
    ///   - oulineColor: 線の色
    ///   - foregroundColor: 縁取りの中の色
    func makeOutLine(strokeWidth: CGFloat, oulineColor: UIColor, foregroundColor: UIColor) {
        let strokeTextAttributes = [
            .strokeColor : oulineColor,
            .foregroundColor : foregroundColor,
            .strokeWidth : strokeWidth,
            .font : self.font
        ] as [NSAttributedString.Key : Any]
        self.attributedText = NSMutableAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
    }
}

見た目があまり美しくないので、静的な用途であればIllustratorなどのアプリケーションでSVG書き出ししたものを使うと良い。

Playground

Playgroundにコードをコピペして実行するとどんな感じが確認できる。

import UIKit

extension UILabel{

    /// makeOutLine
    ///
    /// - Parameters:
    ///   - strokeWidth: 線の太さ。負数
    ///   - oulineColor: 線の色
    ///   - foregroundColor: 縁取りの中の色
    func makeOutLine(strokeWidth: CGFloat, oulineColor: UIColor, foregroundColor: UIColor) {
        let strokeTextAttributes = [
            .strokeColor : oulineColor,
            .foregroundColor : foregroundColor,
            .strokeWidth : strokeWidth,
            .font : self.font
        ] as [NSAttributedString.Key : Any]
        self.attributedText = NSMutableAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
    }
}

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 500, height: 60))
label.font = UIFont.boldSystemFont(ofSize: 50)
label.text = "我が家の猫は7.4kg"
label.makeOutLine(strokeWidth: -2.0, oulineColor: .white, foregroundColor: .blue)

キャプチャ
uilabel-outline

おまけ

NSAttributedString.Key でいろいろ装飾できるので、ドキュメントを読むと面白い。
NSAttributedString.Key

iOSでチラシレイアウトも実現できる。需要はない。
iOSでチラシっぽい価格レイアウトを再現してみた

参考

元ネタ

Custom Label Effects in Swift 4

個人的に毎度読むスライド

最高

Mastering Textkit

5
5
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
5
5