UIView to Image

2017-05-26  本文已影响0人  yhj0129

效果:


92DD32C0C376FC056BBFCAEE14FF639B.jpg

主要代码:

@interface ShopViewController ()

@property(nonatomic,strong)UIView *yView;

@end

@implementation ShopViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initView];

    [self createBtn];

}

-(void)createBtn
{
    UIButton *transferBtn=[[UIButton alloc]initWithFrame:CGRectMake(100,200,100,30)];
    [transferBtn setTitle:@"保存图片" forState:0];
    [transferBtn setTitleColor:[UIColor redColor] forState:0];
    [transferBtn addTarget:self action:@selector(transferBtnEvent) forControlEvents:UIControlEventTouchUpInside ];
    [self.view addSubview:transferBtn];
}

-(void)transferBtnEvent
{
    UIImage *image=[self createViewImage:self.yView];
    UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),nil);
}

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error==nil)
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"图片保存成功" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];

        NSLog(@"保存成功");
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"图片保存失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];

        NSLog(@"保存失败呢");
    }
}

-(UIImage *)createViewImage:(UIView *)yView
{
    UIGraphicsBeginImageContextWithOptions(yView.bounds.size,NO,[UIScreen mainScreen].scale);
    [yView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)initView
{
    self.yView=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH-kmargin*2)];
    self.yView.backgroundColor=[UIColor lightGrayColor];

    // label
    UILabel *tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(10,30,APPW-20,30)];
    tipLabel.text=@"UIViewToUIImage";
    tipLabel.textAlignment=NSTextAlignmentCenter;
    tipLabel.textColor=[UIColor redColor];
    [self.yView addSubview:tipLabel];

    // image
    UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(kmargin*2,kmargin*4+tipLabel.frame.size.height,APPW-kmargin*4,APPH-kmargin*12)];
    image.image=[UIImage imageNamed:@"2.jpg"];
    [self.yView addSubview:image];
}
@end
上一篇下一篇

猜你喜欢

热点阅读