oc之mac中NSView转换为NSimage 与 UIImage转换为UIimage以 总结

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

 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HeroGuo_JP/article/details/51981797

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;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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;
}

 

posted @ 2019-01-29 17:22  sundaysmac  阅读(827)  评论(0编辑  收藏  举报