使用layer.presentationLayer
而不是layer
when renderInContext
。
这是一个用于截取UIView的类别,UIView+Screenshot.h:
//
// UIView+Screenshot.h
//
// Created by Horace Ho on 2012/12/11.
// Copyright (c) 2012 Horace Ho. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
@interface UIView (HHScreenShot)
- (UIImage *)screenshot:(UIDeviceOrientation)orientation isOpaque:(BOOL)isOpaque usePresentationLayer:(BOOL)usePresentationLayer;
@end
@implementation UIView (HHScreenShot)
- (UIImage *)screenshot:(UIDeviceOrientation)orientation isOpaque:(BOOL)isOpaque usePresentationLayer:(BOOL)usePresentationLayer
{
CGSize size;
if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) {
size = CGSizeMake(self.frame.size.width, self.frame.size.height);
} else {
size = CGSizeMake(self.frame.size.height, self.frame.size.width);
}
UIGraphicsBeginImageContextWithOptions(size, isOpaque, 0.0);
if (usePresentationLayer) {
[self.layer.presentationLayer renderInContext:UIGraphicsGetCurrentContext()];
} else {
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
要使用:
UIImage *image = [self.view screenshot:UIDeviceOrientationPortrait
isOpaque:YES
usePresentationLayer:YES];