我的应用程序允许用户前后切换UIImageView,然后用户可以捕获该屏幕。这是我的代码,将屏幕捕获为UIImage

-(UIImage *)imageWithView:(UIView *)view
{
   UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 2.0f);

// I even tried view.layer.presentationLayer but still not working
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


return image;

}

我不使用[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES],因为它速度较慢,有时(当视图不可见时)以黑色绘制屏幕截图。

但是renderInContext的问题是UIImageView ( imageView.layer.zPosition = 0.01;etc )之间改变的Z位置。在我的iPhone屏幕上,当我将值分配给zPosition时,此功能可以正常工作,但是在捕获屏幕上,结果却是错误的。

无论如何,我可以解决这个问题吗?提前致谢

编辑:
这是我在捕获屏幕截图之前尝试做的事情。我使用此代码在另一个ImageView之前显示一个ImageView。
-(void)bringOneLevelUp:(UIImageView*)imageView
{
//_imgArray is sorted by Z position order (small to big)
    NSUInteger currentObjectIndex = [_imgArray indexOfObject:imageView];


if(currentObjectIndex+1< _imgArray.count){

UIImageView *upperImageView = [_imgArray objectAtIndex:currentObjectIndex+1];


    CGFloat currentZIndex = imageView.layer.zPosition;
    CGFloat upperZIndex= upperImageView.layer.zPosition;

    imageView.layer.zPosition = upperZIndex;
    upperImageView.layer.zPosition = currentZIndex;


// swap position in array
[_imgArray exchangeObjectAtIndex:currentObjectIndex withObjectAtIndex:currentObjectIndex+1];

}

}

就像我之前解释过的一样,该代码在电话屏幕中的结果是正确的。 newImageView在lastImageView的前面。但是当我通过renderInContext捕获屏幕截图时。他们不是。

最佳答案

迅捷4.2

@RameshVel的答案为我工作,将其翻译为 Swift ,也许有人需要这个:

 UIGraphicsBeginImageContext(drawingCanvas.frame.size)
 self.renderInContext(ct: UIGraphicsGetCurrentContext()!)

 guard let image = UIGraphicsGetImageFromCurrentImageContext() else {return}
 UIGraphicsEndImageContext()

并在renderInContext函数中:
 func renderInContext(ct:CGContext){

    ct.beginTransparencyLayer(auxiliaryInfo: nil)

    // descendant ordered list of views based on its z-position
    let orderedLayers = self.view.subviews.sorted(by: {
        $0.layer.zPosition < $1.layer.zPosition
    })

    for l in orderedLayers {
        l.layer.render(in: ct)
    }
    ct.endTransparencyLayer()
}

如果要绘制和添加图层,则可以使用 CALayers 来实现:
 UIGraphicsBeginImageContext(drawingCanvas.frame.size)
 //Canvas is a custom UIView for drawing
 self.renderInContext(ct: UIGraphicsGetCurrentContext()!, canvas: canvas)

 guard let image = UIGraphicsGetImageFromCurrentImageContext() else {return}
 UIGraphicsEndImageContext()

renderInContext函数:
func renderInContext(ct:CGContext, canvas:CustomCanvas){

    ct.beginTransparencyLayer(auxiliaryInfo: nil)
    let layers:[CALayer] = canvas.layer.sublayers!

    let orderedLayers = layers.sorted(by: {
        $0.zPosition < $1.zPosition
    })

    for v in orderedLayers {
        v.render(in: ct)
    }
    ct.endTransparencyLayer()
}

10-07 21:31