LoginSignup
10
8

More than 5 years have passed since last update.

CATextLayerの上下中央揃え

Last updated at Posted at 2014-11-30

CATextLayer の上下中央揃えにはまっていましたが、なんとかうまい具合に行きそうなのでちょっと書いてみます。CATextLayerの左右中央揃えはメソッドも用意されていてすぐできるんですが、上下中央は情報も少なく(あってもちょっとトリッキー)、そこまで完璧を求めていなかったのでシンプルに出来る方法を探りました。

前提

  • CAShapeLayerで作成した shapeLayer があります。そして、そのframeは bodyRect という変数で宣言しています。
  • bodyRectのサイズは常に変わるので、textLayerのサイズを固定にすることはできません。
  • shapeLayerの上に上下左右中心に揃えたテキストを置きたいと思っていました。

どんなことをやったか

textの表示領域を取得して、CATextLayerのサイズをその領域に書きだすことで上下中央に配置する。

説明付きコード

// とりあえず、fontと表示したいテキストを用意
let font = UIFont.systemFontOfSize(20.0)
let text = "T"

// 上記で用意したfontを利用した場合のテキストのサイズを取得
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = font
let size = text.sizeWithAttributes(attributes)

// テキストのサイズから表示するframeを作成
let x = CGRectGetMinX(bodyRect) + (CGRectGetWidth(bodyRect) - size.width) / 2
let y = CGRectGetMinY(bodyRect) + (CGRectGetHeight(bodyRect) - size.height) / 2
let height = size.height
let width = size.width
let frame = CGRectMake(x, y, width, height)

// CATextLayerを作っていきます。
let textLayer = CATextLayer()
textLayer.string = text
textLayer.font = font
// 解説1
textLayer.fontSize = font.pointSize
textLayer.foregroundColor = UIColor.whiteColor().CGColor
textLayer.frame = frame
// 左右中央揃えです
textLayer.alignmentMode = kCAAlignmentCenter
// スケールの調整
textLayer.contentsScale = UIScreen.mainScreen().scale
shapeLayer.addSublayer(textLayer)
return shapeLayer

解説1

textLayer.font = fontでフォントを指定しているのでサイズもセットしているのかなと思っていたら、ちゃんとtextLayer.fontSizeで指定しないと反映されませんでした汗 これが原因で1.5時間ははまった〜。

全体を通して

とりあえずの方法です。でも、助かる人もいるかなと思ってコミュニティにシェアしました。もっとしっかりfontのbaselineの調整などもやったほうが正確かもしれませんが。

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