▼iPhoneプログラミングメモ▼

文字列の描画


文字列の描画を行うプログラムを作成する。


ソースコードの記述
StringEx.h
#import <UIKit/UIKit.h>

//StringExの宣言
@interface StringEx : UIView {
}
@end

StringEx.m
#import "StringEx.h"

//StringExの実装
@implementation StringEx

//初期化
- (id)initWithFrame:(CGRect)frame {
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor=[UIColor whiteColor];
    }
    return self;
}

//メモリ解放
- (void)dealloc {
    [super dealloc];
}

//色の指定
- (void)setColor_r:(int)r g:(int)g b:(int)b {
    [[UIColor colorWithRed:r/255.0f green:g/255.0f 
        blue: b/255.0f alpha:1.0f] set];
}

//文字列の描画
- (void)drawString:(NSString*)string 
    x:(float)x y:(float)y font:(UIFont*)font {
    [string drawAtPoint:CGPointMake(x,y) withFont:font];
}

//描画
- (void)drawRect:(CGRect)rect {
    //フォントの生成
    UIFont* font=[UIFont systemFontOfSize:24];

    //文字色の指定
    [self setColor_r:0 g:0 b:0];
    
    //画面サイズの取得
    CGSize scrSize=self.frame.size;
    
    //文字列の描画
    [self drawString:[NSString stringWithFormat:@"画面サイズ:%dx%d",
        (int)scrSize.width,(int)scrSize.height] x:0 y:0 font:font];

    //文字幅の取得
    CGSize strSize=[@"A" sizeWithFont:font];
    [self drawString:[NSString stringWithFormat:@"文字幅:%d",
        (int)strSize.width] x:0 y:30 font:font]; 
       
    //12ドットの文字列の描画
    font=[UIFont systemFontOfSize:12];
    [self setColor_r:255 g:0 b:0];
    [self drawString:@"12dot" x:0 y:30*2 font:font]; 

     //16ドットの文字列の描画
    font=[UIFont systemFontOfSize:16];
    [self setColor_r:0 g:255 b:0];
    [self drawString:@"16dot" x:0 y:30*3 font:font]; 

    //24ドットの文字列の描画
    font=[UIFont systemFontOfSize:24];
    [self setColor_r:0 g:0 b:255];
    [self drawString:@"24dot" x:0 y:30*4 font:font]; 
}
@end





−戻る−