52
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UILabelの文字に枠をつけ、袋文字(縁取り文字)を作る

Last updated at Posted at 2014-04-27

UILabelのサブクラスを用いて、下図のような袋文字(縁取り文字)を描画します。

スクリーンショット 2014-04-27 20.59.47.png

まず、UILabelを継承したサブクラスを作ります。

UIOutlineLabel.h
@import UIKit;

@interface UIOutlineLabel : UILabel

@property(nonatomic) UIColor *outlineColor;
@property(nonatomic) NSInteger outlineSize;

@end
UIOutlineLabel.m
#import "UIOutlineLabel.h"

@implementation UIOutlineLabel

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // デフォルト値
        _outlineColor = [UIColor whiteColor];
        _outlineSize = 2;
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect
{
    CGContextRef cr = UIGraphicsGetCurrentContext();
    UIColor *textColor = self.textColor;

    CGContextSetLineWidth(cr, _outlineSize);
    CGContextSetLineJoin(cr, kCGLineJoinRound);
    CGContextSetTextDrawingMode(cr, kCGTextStroke);
    self.textColor = _outlineColor;
    [super drawTextInRect:rect];

    CGContextSetTextDrawingMode(cr, kCGTextFill);
    self.textColor = textColor;
    [super drawTextInRect:rect];
}

@end

以下のように利用します。

    UIOutlineLabel *label = [[UIOutlineLabel alloc] init];

    // 通常の設定
    label.frame = CGRectMake(0, 0, 100, 50);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:30];
    label.text = @"Hello world";

    // 袋文字用の設定
    label.outlineColor = [UIColor blackColor]; // 縁取りの色
    label.outlineSize = 3; // 縁取りの太さ

    [self.view addSubview:label];

Interface Builderを用いる場合はIdentity InspectorのCustom ClassにUIOutlineLabelを設定します。

スクリーンショット 2014-04-27 20.33.53.png

52
50
5

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
52
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?