添加文本到UIImage ...错误的地方

时间:2017-01-24 19:39:27

标签: ios objective-c uiimage uigraphicscontext

我试图将文字绘制到*l。下面的方法有效,但文本已关闭。我在框架的中心有self.image = [self drawText]标签。 -(UIImage*) drawText{ UIGraphicsBeginImageContextWithOptions(_creatorImageView.image.size, false, _creatorImageView.image.scale); [_creatorImageView.image drawInRect:CGRectMake(0,0,_creatorImageView.image.size.width, _creatorImageView.image.size.height)]; NSLog(@"Caption ARRY: %@", _creatorImageView.captionArray); for (UILabel *l in _creatorImageView.captionArray){ NSLog(@"%f %f", l.frame.origin.x, l.frame.origin.y); CGRect rect = CGRectMake(l.frame.origin.x, l.frame.origin.y, _creatorImageView.image.size.width, _creatorImageView.image.size.height); [l.textColor set]; CGFloat radians = atan2f(l.transform.b, l.transform.a); CGFloat degrees = radians * (180 / M_PI); //CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeScale(l.transform.tx, l.transform.ty)); //CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeRotation(degrees)); //NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; //[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; //[paragraphStyle setAlignment:NSTextAlignmentCenter]; NSDictionary *attributes = @{ NSFontAttributeName: l.font, NSForegroundColorAttributeName: l.textColor, NSBackgroundColorAttributeName: l.backgroundColor}; //NSParagraphStyleAttributeName:paragraphStyle}; [l.text drawInRect:rect withAttributes:attributes]; NSLog(@"TEXT: %@", l.text); } UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } 后,文字位于图片的左上角。

{{1}}

1 个答案:

答案 0 :(得分:0)

您正在使用代码

[l.text drawInRect:rect withAttributes:attributes];

绘制文字。您指定的rect矩形控制文本的绘制位置,位于上下文的坐标中(其中0,0是上下文的左上角。)

如果您希望文本在上下文中居中,请根据上下文计算中心,并调整矩形的原点以使文本居中。

我会让你去算算数学。它只是几行代码。