LoginSignup
10
10

More than 5 years have passed since last update.

Swift 丸アイコン内、テキストセンター描画

Last updated at Posted at 2015-06-18

Swift 丸アイコン内、テキストセンター描画

UIViewのカスタムクラスにて、overrideしたdrawRect内で、

// 丸描画
let roundRect = UIBezierPath(roundedRect: CGRectMake(1, 1, 28, 28), cornerRadius: 10)
UIColor.blueColor().setStroke()
roundRect.lineWidth = 2
roundRect.stroke()

// フォント属性
let fontAttr = [NSFontAttributeName: UIFont.systemFontOfSize(10)]
// テキスト
let str = self.initial_txt! as NSString!
// サイズ取得
let size = str.sizeWithAttributes(fontAttr)

let x_pos = (roundRect.bounds.size.width - size.width) / 2
let y_pos = (roundRect.bounds.size.height - size.height) / 2

// テキスト描画
str.drawAtPoint(CGPointMake(roundRect.bounds.origin.x + x_pos, roundRect.bounds.origin.y + y_pos),
    withAttributes: fontAttr)

結果

initial.png

参考

How to use NSString drawInRect to center text?
http://stackoverflow.com/questions/477509/how-to-use-nsstring-drawinrect-to-center-text

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