iphone - 如何在矩形中绘制和缩放文本

标签 iphone ios text graphics

我的问题很简单。我有一个矩形,例如(0.0, 0.0, 300, 45), 并且需要绘制一个字符串,例如该矩形中心的“文本”。 “文本”的高度必须适合矩形的高度。

困难的部分是:矩形可以缩放。 “文本”的大小必须缩放为矩形的大小。

我可以按照下面的代码在矩形的中心绘制字符串,但难点是我无法管理随着矩形大小而变化的“文本”字体大小。

[@"文本"drawInRect:textRect withFont:font];

我想在矩形中绘制文本,而不是标签,用户可以用手指缩放矩形大小,最后,我会在图像上按比例绘制文本,我认为标签不适用于这些功能。

谁有好的解决办法?

谢谢!

更新:

实际上,我需要在大图上按比例绘制文字,而不仅仅是在iphone屏幕上显示,请看下面的代码:

UIImageVIew *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 320)];

imageView.image = [UIImage imageNamed:@"LargeSizeImage"]; // Image size = 2048 *2048

[self.view addSubview:imageView];

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 45)];

textLabel.text = @"Text";

[self.view addSubviews:textLabel];

// Draw text on image

UIGraphicsBeginImageCurrentContext(imageView.image.size);(2048 * 2048)

[imageView.image drawInRect:CGRectMake(0, 0, 2048, 2048)];

CGRect scaleRect = CGRectMake(10 * scaleFactor, 10 *scaleFactor, textLabel.bounds.size.width * scaleFactor, text.Label.bounds.size.height *scaleFactor);

UIFont *font = [UIFont systemOfSize:**?**];

[textLabel.text drawInRect:scaleRect withFont:font];

...................... ………… ............

我的问题是如何确定字体大小?

最佳答案

UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 300, 45)];
text.backgroundColor = [UIColor clearColor];
text.font = [UIFont systemFontOfSize:45];
text.textAlignment =  UITextAlignmentCenter;
text.text = @"TEXT";
[self.view addSubview:text];

可能会得到你感兴趣的效果。

编辑

实际上,如果您调整正方形的大小,您可以动态调整文本的大小。在调整大小的方法中,只需为 UILabel 添加这些代码行即可触发调整大小。

text.frame = CGRectMake(0.0, 0.0, rect.frame.size.width, rect.frame.size.height);
text.font = [UIFont systemFontOfSize:rect.frame.size.height];

rect 是我用来描述您正在调整大小的矩形。

关于iphone - 如何在矩形中绘制和缩放文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11282709/

相关文章:

iphone - CoreBluetooth 中不允许广告 key 'Manufacturer Data'

android - Titanium Mobile 中用户凭证的数据库与属性

iphone - 从 C 函数返回 NSString

iphone - iOS 6 上的 MapKit 崩溃

iphone - 在 iPhone 和蓝牙设备之间使用蓝牙 HFP 的 Push-To-Talk (PTT) 应用程序

android - 如何提高 Android/iOS/etc 使用 web 服务的性能?

text - 当文本换行到两行时, block 元素占据全宽

python - 高效的叠瓦算法

javascript - 如何使用 JavaScript 在多个 HTML 页面中重复使用格式化文本?

javascript - 根据目标距离计算 iOS 上的到达时间