十 iOS之 截屏

有的app中會需要有一個截屏的小功能,下面看看代碼怎麼寫

給UIImage添加一個類目,寫一個截屏的方法

/**
 控件截屏

 @param view 傳入的View
 @return 截屏圖片
 */
+ (UIImage *)imageWithCaputureView:(UIView *)view
{
    // 開啓位圖上下文
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);

    // 獲取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 把控件上的圖層渲染到上下文,layer只能渲染
    [view.layer renderInContext:ctx];

    // 生成一張圖片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 關閉上下文
    UIGraphicsEndImageContext();

    return image;


}

然後在控制器裏直接調用這個方法就行了,比如把截屏的圖片寫到桌面上

  //調用UIImage類目方法截屏
    UIImage * imageNew = [UIImage imageWithCaputureView:self.view];
    //圖片質量 : 1 最高
    NSData * data = UIImageJPEGRepresentation(imageNew, 1);
    //寫入電腦桌面
    [data writeToFile:@"/Users/mac/Desktop/image.png" atomically:YES];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章