我有以下代码,我想更聪明/数学和灵活。我想将我在圆圈中选择的文本居中,我还想让圆圈的半径取决于圆圈内文本的大小(字符串有多少个字符)。有什么建议我怎么做?
//Add text
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(location.x, location.y, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
[yourLabel setText:@"Jack"];
[self.view addSubview:yourLabel];
// create new CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [[self makeCircleAtLocation:location radius:50.0] CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 3.0;
答案 0 :(得分:1)
如果您想知道文本的大小,只需在NSString对象中使用sizeWithFont:
方法。
NSString *someString = @"some string";
CGSize stringBounds = [someString sizeWithFont:yourLabel.font];
然后你可以确定你应该绘制圆圈的大小。
答案 1 :(得分:1)
假设您希望标签和圆圈位于“位置”点的中心位置:
//Add text
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
[yourLabel setText:@"Jack"];
yourLabel.textAlignment = UITextAlignmentCenter;
yourLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
yourLabel.center = location;
[self.view addSubview:yourLabel];
这应该使你的标签居中,我没有测试它。
对于圆的大小,您可以使用
获取文本的大小- (CGSize)sizeWithFont:(UIFont *)font
表示ios6和ios7
- (CGSize)sizeWithAttributes:(NSDictionary *)attributes
并以param的形式传入标签的字体。对于ios7,传递这样的字体
@{NSFontAttributeName:yourLabel.font}
使用返回的大小来确定圆的半径(我建议使用size.width / 2加上一些额外的填充)。
答案 2 :(得分:0)
NSString *objectString = @"Jack Nicholson";
UIFont *font = [UIFont fontWithName: @"Trebuchet MS" size: 14.0f];
CGSize stringSize = [objectString sizeWithFont:font];
//Add text
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(location.x - (stringSize.width/2), location.y - (stringSize.height/2), 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:font];
[yourLabel setText:objectString];
[self.view addSubview:yourLabel];
// create new CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [[self makeCircleAtLocation:location radius:stringSize.width] CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 3.0;