在UIImage中绘制旋转和缩放的UILabel文本

时间:2013-11-27 11:52:13

标签: ios objective-c uiscrollview uiimage uilabel

我有一个UIScrollView,其中UIImageView位于我获得裁剪的UIImage的位置(考虑缩放,偏移,边界,......)。另一方面,我有UILabel我可以在UIScrollView上的任何地方旋转,捏和平移。当我尝试在裁剪的UIImage(大于屏幕尺寸)内生成带有标签文本(带有原始/等效位置,旋转......)的最终图像时出现问题。

我已经尝试了一切。这是我尝试定位文本的最后一次尝试,但它总是放错地方。

// Compute rect to draw the text inside
CGSize imageSize = inImage.size;
NSDictionary *attr = @{NSForegroundColorAttributeName: fontColor, NSFontAttributeName: textFont};
CGSize textSize = [text sizeWithAttributes:attr];
CGRect textRect = CGRectMake(labelCenterPoint.x, labelCenterPoint.y, textSize.width, textSize.height);

// Create the image
UIGraphicsBeginImageContext(imageSize);
[inImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];

// Rotate text from center
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM( context, 0.5f * textSize.width, 0.5f * textSize.height ) ;
CGContextRotateCTM(context, rotation);
[text drawInRect:CGRectIntegral(textRect) withAttributes:attr];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我认为问题是textRect来源。我是否也必须UILabel subView UIScrollView textRect并且相对于UIScrollView参数设置 // Calculate the relative position of the UILabel with respect // to the ScrollView that contains the image float xPosition = label.frame.origin.x - scrollView.frame.origin.x; float yPosition = label.frame.origin.y - scrollView.frame.origin.y; // Calculate the proportion to apply to the position // (the image is bigger than screen) float xProportion = image.frame.size.width / scrollView.frame.size.width; float yProportion = image.frame.size.height / scrollView.frame.size.height; UIImageView *testView = [[UIImageView alloc] initWithImage:image]; UILabel *tempLabel = [[UILabel alloc] initWithFrame: CGRectMake((xPosition*xProportion), (yPosition*yProportion), label.frame.size.width*xProportion, label.frame.size.height*yProportion)]; tempLabel.text = label.text; tempLabel.font = [UIFont fontWithName:label.font.fontName size:label.font.pointSize*3]; tempLabel.textColor = label.textColor; tempLabel.textAlignment = NSTextAlignmentCenter; tempLabel.transform = CGAffineTransformMakeRotation(rotation); tempLabel.adjustsFontSizeToFitWidth = YES; tempLabel.minimumScaleFactor = 0.05; [testView addSubview:tempLabel]; UIGraphicsBeginImageContext(testView.image.size); [testView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *imageWithText = UIGraphicsGetImageFromCurrentImageContext(); 来源?还是我错过了什么?有更好的方法吗?。

提前致谢!

修改 我终于找到了一个可接受的解决方案(虽然不是太精确)。我认为问题在于两个现有的坐标系,所以我尝试了另一种方法:

{{1}}

我希望这可以帮助某人。当然欢迎所有建议。

0 个答案:

没有答案