2017-12-30 38 views
0

を描く:私はこのコードを使用していますコアグラフィックスを使用して中心のテキスト(モバイルデバイス)

CGRect screenRect = [[UIScreen mainScreen] bounds]; 
CGFloat screenWidth = screenRect.size.width; 
CGFloat screenHeight = screenRect.size.height; 
NSString * text = @"text"; 
CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:RETICLE_ALPHA].CGColor); 
[text drawAtPoint:CGPointMake(screenWidth/2, screenHeight/2) withFont: [UIFont systemFontOfSize:22.0]]; 

は、iOS用の中心に「テキスト」を作成します。

しかし、テキストが実際にはまったく中央に配置されていないので、上のコードをどのように編集して中心の配置を実際に行うかわかりません。

申し訳ありませんが、愚かな質問のために、私は問題の作業例を見つけませんでした。&私はCore Graphicsを初めて使用しています。

+1

、私は[関連する質問](https://stackoverflow.com/a/48035791/1271826)に私の答えで指摘するように、(a)は、あなたが 'drawAtPoint使用しないでください。withFontを: 'ではなく、' drawAtPoint:withAttributes: '; (b)CoreGraphics APIではなく、 'attributes'辞書にフォントの色を指定する必要があります。 – Rob

答えて

2

テキストを画面のサイズから差し引く必要があり、次に2で割る必要があるため、テキストが中央に配置されません。次に、コードを修正しようとしました。ところで

CGRect screenRect = [[UIScreen mainScreen] bounds]; 
CGFloat screenWidth = screenRect.size.width; 
CGFloat screenHeight = screenRect.size.height; 
NSString * text = @"text"; 

CGFloat minHeight = 40; 
float widthIs = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight) options:NSStringDrawingUsesLineFragmentOrigin 
attributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:22.0] } 
context:nil].size.width; 
CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor); 
[text drawAtPoint:CGPointMake((screenWidth - widthIs)/2, (screenHeight - minHeight)/2) withFont: [UIFont systemFontOfSize:22.0]]; 
関連する問題