2012-09-30 98 views
2

我試圖將圖像添加到圖像,但將uilabel作爲子視圖添加到uiimageview。 我已經做到了,但我想將它們保存爲圖像; 我在上下文中使用渲染,但它不工作。將uilabel和uiimageview保存爲uiimage

這裏是我的代碼:

UIImage * img = [UIImage imageNamed:@"IMG_1650.JPG"]; 

     float x = (img.size.width/imageView.frame.size.width) * touchPoint.x; 
     float y = (img.size.height/imageView.frame.size.height) * touchPoint.y; 

     CGPoint tpoint = CGPointMake(x, y); 

     UIFont *font = [UIFont boldSystemFontOfSize:30]; 
     context = UIGraphicsGetCurrentContext(); 
     UIGraphicsBeginImageContextWithOptions(img.size, YES, 0.0); 
     [[UIColor redColor] set]; 

     for (UIView * view in [imageView subviews]){ 
      [view removeFromSuperview]; 
     } 
      UILabel * lbl = [[UILabel alloc]init]; 
     [lbl setText:txt]; 
     [lbl setBackgroundColor:[UIColor clearColor]]; 
     CGSize sz = [txt sizeWithFont:lbl.font]; 
     [lbl setFrame:CGRectMake(touchPoint.x, touchPoint.y, sz.width, sz.height)]; 
     lbl.transform = CGAffineTransformMakeRotation(-M_PI/4); 

     [imageView addSubview:lbl]; 
     [imageView bringSubviewToFront:lbl]; 
     [imageView setImage:img]; 
     [imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
     [lbl.layer renderInContext:UIGraphicsGetCurrentContext()]; 

     UIImage * nImg = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
     UIImageWriteToSavedPhotosAlbum(nImg, nil, nil, nil); 

回答

5

嘗試下面的代碼。這個對我有用。

UIGraphicsBeginImageContext(imageView.bounds.size); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *bitmap = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

P.S.我認爲你不需要renderInContextUILabel層。