将UITextView转换为图像

时间:2013-10-12 13:36:14

标签: ios uiimageview uiimage uitextview

我有一个UITextView和一个UIImageView,我想将其转换为单个图像进行分享。

SaveImageView,是ImageView,我想保存textview的图像。

Textview可以在屏幕上移动它,所以我决定保存它们的最终位置并将其提供给SaveImageView。

首先在图像中转换UItextView并保存其位置。

然后,我想将两个imageview加入一个图像中。

self.SaveTextView.frame = self.textView.frame;


UIGraphicsBeginImageContext (self.textView.bounds.size);

[self.textView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();


self.SaveTextView.image=resultingImage;

//加入两个uiimageview

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);

[self.BaseImageView.image drawInRect:CGRectMake(0, 0, self.BaseImageView.frame.size.width, self.BaseImageView.frame.size.height)];

[self.SaveTextView.image drawInRect:CGRectMake(self.SaveTextView.frame.origin.x, self.SaveTextView.frame.origin.y, self.SaveTextView.frame.size.width, self.SaveTextView.frame.size.height)];


_SaveImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

问题是我在textview中写的地方不在保存图像的同一位置,带文字的图像稍微移动,当它应该是我写的确切位置,而不是找到哪里是错误。

任何帮助??

2 个答案:

答案 0 :(得分:2)

尝试实现此方法并在superview上调用它:

@implementation UIView (ScreenShot)

- (UIImage *)screenShot
{
  UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return image;
}

@end

答案 1 :(得分:1)

试试这个......

//Make Label
UILabel *_labelTimeOutName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 428, 32)];
_labelTimeOutName.text = @"Your label text here";
_labelTimeOutName.minimumScaleFactor = 0.5;
_labelTimeOutName.numberOfLines = 1;
_labelTimeOutName.textColor = [UIColor whiteColor];
_labelTimeOutName.backgroundColor = [UIColor clearColor];
_labelTimeOutName.font  = [UIFont fontWithName:@"TrebuchetMS-Bold" size:24];
_labelTimeOutName.textAlignment = NSTextAlignmentCenter;

//add label inside a temp View
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 428, 32)];
tempView.backgroundColor = [UIColor clearColor];
[tempView addSubview:_labelTimeOutName];

//render image
//CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsBeginImageContextWithOptions(tempView.bounds.size, tempView.opaque, 0.0);
// The view to be rendered
[[tempView layer] renderInContext:UIGraphicsGetCurrentContext() ]; //context];
// Get the rendered image
//////////////////////////////////////////////////////////////////////
UIImage *FinalTextIamge = UIGraphicsGetImageFromCurrentImageContext();
//////////////////////////////////////////////////////////////////////
UIGraphicsEndImageContext();

享受!