見出しはそれをかなり説明しています。テキストを描いている画像があります。画像のサイズに合わせてテキストのサイズを変更し、画像自体よりも少し短いフォントの高さを取得する方法を見つけたいと思います。
11125 次
3 に答える
20
OK、反復は避けられないと考えるすべての人のために:
NSString *string = @"The string to render";
CGRect rect = imageView.frame;
UIFont *font = [UIFont fontWithSize:12.0]; // find the height of a 12.0pt font
CGSize size = [string sizeWithFont:font];
float pointsPerPixel = 12.0 / size.height; // compute the ratio
// Alternatively:
// float pixelsPerPoint = size.height / 12.0;
float desiredFontSize = rect.size.height * pointsPerPixel;
// Alternatively:
// float desiredFontSize = rect.size.height / pixelsPerPoint;
desiredFontSize
高さが指定された長方形の高さと正確に同じであるポイント単位のフォントサイズが含まれます。見栄えを良くするために、たとえば 0.8 を掛けて、フォントを rect の実際のサイズよりも少し小さくすることができます。
于 2012-05-03T04:02:08.453 に答える
1
ここから
CGFloat GetLineHeightForFont(CTFontRef iFont)
{
CGFloat lineHeight = 0.0;
check(iFont != NULL);
// Get the ascent from the font, already scaled for the font's size
lineHeight += CTFontGetAscent(iFont);
// Get the descent from the font, already scaled for the font's size
lineHeight += CTFontGetDescent(iFont);
// Get the leading from the font, already scaled for the font's size
lineHeight += CTFontGetLeading(iFont);
return lineHeight;
}
これを使用するには、ポイント サイズを推測し、行の高さを見つけます (行間を気にする場合と気にしない場合があります)。次に、答えと高さの比率を使用して、ポイント サイズをスケーリングします。高さが正確であることが保証されているとは思いません-正確であることを気にする場合は、十分に近くなるまで反復する必要があります(新しいサイズを新しい推測として使用してください)。
于 2012-05-02T18:34:29.290 に答える
0
注:これは、フォント サイズが常に CGRect のポイント サイズよりも小さいことを前提としています。その仮定を修正するために、必要に応じてメソッドを調整します。
これを試して。フォントを作成する 3 つの主要な方法のいずれかで機能します。かなり自明ですが、increment はチェック間で減少させたい量です。正確なサイズを気にしない場合は、その数値を大きくして速度を上げてください。気にする場合は、精度を上げるために小さくしてください。
- (UIFont *)systemFontForRectHeight:(CGFloat)height
increment:(CGFloat)increment {
UIFont *retVal = nil;
for (float i = height; i > 0; i = i - increment) {
retVal = [UIFont systemFontOfSize:i];
if ([retVal lineHeight] < height) break;
}
return retVal;
}
- (UIFont *)boldSystemFontForRectHeight:(CGFloat)height
increment:(CGFloat)increment {
UIFont *retVal = nil;
for (float i = height; i > 0; i = i - increment) {
retVal = [UIFont boldSystemFontOfSize:i];
if ([retVal lineHeight] < height) break;
}
return retVal;
}
- (UIFont *)fontNamed:(NSString *)name
forRectHeight:(CGFloat)height
increment:(CGFloat)increment {
UIFont *retVal = nil;
for (float i = height; i > 0; i = i - increment) {
retVal = [UIFont fontWithName:name size:i];
if ([retVal lineHeight] < height) break;
}
return retVal;
}
于 2012-05-02T19:01:08.560 に答える