您的位置:首页 > 产品设计 > UI/UE

NSView转换为NSimage 与 UIImage转换为UIimage 总结

2016-07-21 12:44 316 查看
Cocoa框架下NSView转换为NSimage 与 UIKit框架下UIView转化为UIImage对比总结

Cocoa框架下:

/*!
*  @author GJH, 16-07-21
*
*  NSview 转换为 NSimage
*
*  @param m_view 需要转换的NSView对象
*
*  @return 所要生成的NSimage
*/
-(NSImage *)viewToImage:(NSView *)m_view
{
//    焦点锁定
[m_view lockFocus];
//    生成所需图片
NSImage *image = [[NSImage alloc]initWithData:[m_view dataWithPDFInsideRect:[m_view bounds]]];
[m_view unlockFocus];

//   保存图片到本地
[image lockFocus];
NSBitmapImageRep *bits = [[NSBitmapImageRep alloc]initWithFocusedViewRect:[m_view bounds]];
[image unlockFocus];
//    设置要用到的props属性
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSImageCompressionFactor];
//    转化为Data保存
NSData *imageData = [bits representationUsingType:NSPNGFileType properties:imageProps];
//    保存路径必须是绝对路径相对路径不行
[imageData writeToFile:[[NSString alloc]initWithFormat:@"/Users/gjh/Desktop/ImageData/test%d.png",1] atomically:YES];
return image;

}


UIKit框架下:

/*!
*  @author GJH, 16-07-21
*
*  UIView转化为UIImage
*
*  @param mView 需要转化的View
*
*  @return 生成的UIimage
*/
- (UIImage *)callBackImageWithView:(UIView *)mView{
//    创建画板与视图一致
UIGraphicsBeginImageContextWithOptions(mView.bounds.size, YES, [UIScreen mainScreen].scale);
//    将视图画在画板上
[mView drawViewHierarchyInRect:mView.bounds afterScreenUpdates:YES];
//    将画板转化为UIimage
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: