[英]iOS : CGRect of a Specific Text in a String of a UILabel
我想知道字符串在rect中绘制后将是什么帧。
NSString *string = @"This is a sample text.";
UILabel *label = [[UILabel alloc] init];
label.text = string;
// do some setups here
在drawInRect:
方法中,我想检索特定单词的框架。 假设我想知道sample
的rect来自This is a sample text.
串。
这是一个示例UILabel
,我想知道红框内文本的框架。 谢谢!
你可以通过决定一个字符的特定像素来做到这一点
即假设字符'R'在X坐标中占8个像素。 像这样通过8* number of characters in the label
乘以8* number of characters in the label
就可以得到帧
1]Create a CGRect.
CountRect=CGRectMake(rect.origin.x,
rect.origin.y+22 + (rect.size.height - height)/2,
rect.size.width,
(rect.size.height - height)/2);
2]set NSString which contain string.(your case only contain sample)
NSString* myNewString;
3]set NSString to CGRect.
[myNewString drawInRect:CountRect
withFont:fontlineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
[myNewString drawInRect:CountRect withAttributes:attributes];
你没有得到UILabel中特定单词的框架,你只能获得UILabel框架,你将字符串分成单词,就像这样
NSArray *stringArray = [originalString componentsSeparatedByString:@" "];
为每个UILabel添加UILabel和文本和框架
int x=0;
int y=0;
for(int i=0;i<stringArray.count;i++)
{
CGSize size =[[stringArray objectAtIndex:i] sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:fontSize ]];
UILabel *label=[[UILabel alloc]init];
if(x+size.width >320)
{
y=y+size.height;
x=0;
}
label.frame = CGRectMake(x,y,size.width,size.height);
x=x+size.width;
label.text=[wordsArray objectAtIndex:i];
label.textColor=UIColorFromRGB(0x3a5670);
label.font=[UIFont fontWithName:@"ChaparralPro-Bold" size:fontSize];
label.backgroundColor=[UIColor clearColor];
[self.view addSubview:label];
[label release];
}
您可以使用函数获取字符串的大小:
- (CGSize)sizeWithFont:(UIFont *)font;
CGSize wordSize = [@"sample" sizeWithFont:font];
您可以遍历所有单词和换行符,并相应地获取每个单词的帧
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.