代码之家  ›  专栏  ›  技术社区  ›  cduck Daniel

如何拍摄uiview的屏幕截图?

  •  130
  • cduck Daniel  · 技术社区  · 16 年前

    我想知道我的iPhone应用程序如何拍摄特定 UIView 作为一个 UIImage .

    我试过这个代码,但得到的只是一个空白图像。

    UIGraphicsBeginImageContext(CGSizeMake(320,480));
    CGContextRef context = UIGraphicsGetCurrentContext();
    [myUIView.layer drawInContext:context];
    UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    myUIView 具有尺寸320x480和一些子视图。 正确的方法是什么?

    15 回复  |  直到 7 年前
        1
  •  72
  •   Kendall Helmstetter Gelner    16 年前

    我想你可能想要 renderInContext 不是 drawInContext . DrawInContext更像是一种可以重写的方法…

    请注意,它可能在所有视图中都不起作用,特别是在一年左右以前,当我尝试将它与实时摄像头视图一起使用时,它不起作用。

        2
  •  180
  •   Cœur Gustavo Armenta    9 年前

    iOS7有一个新方法,允许您将视图层次绘制到当前图形上下文中。这可用于快速获取ui图像。

    我在上实现了一个类别方法 UIView 将视图作为 UIImage :

    - (UIImage *)pb_takeSnapshot {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    
        // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    

    它比现有的要快得多 renderInContext: 方法。

    参考文献: https://developer.apple.com/library/content/qa/qa1817/_index.html

    Swift更新 :执行相同操作的扩展名:

    extension UIView {
    
        func pb_takeSnapshot() -> UIImage {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
    
            drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
    
            // old style: layer.renderInContext(UIGraphicsGetCurrentContext())
    
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    

    Swift 3的更新

        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
    
        drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    
        3
  •  61
  •   Tibidabo    14 年前

    你需要捕捉 关键窗口 对于屏幕截图或uiview。你可以在里面做 视网膜分辨率 使用uigraphicsBeginImageContextWithOptions并将其比例参数设置为0.0f。它总是以本机分辨率捕获(iPhone4和更高版本的视网膜)。

    这个屏幕截图是全屏的(关键窗口)

    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    此代码以本机分辨率捕获uiview

    CGRect rect = [captureView bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [captureView.layer renderInContext:context];   
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    如果需要的话,这会将uiimage以JPG格式保存在应用程序的文档文件夹中,质量达到95%。

    NSString  *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];    
    [UIImageJPEGRepresentation(capturedImage, 0.95) writeToFile:imagePath atomically:YES];
    
        4
  •  21
  •   san    12 年前

    IOS7之后,我们有以下默认方法:

    - (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
    

    调用上面的方法比自己将当前视图的内容呈现为位图图像要快。

    如果要对快照应用图形效果(如模糊),请使用 drawViewHierarchyInRect:afterScreenUpdates: 方法代替。

    https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html

        5
  •  10
  •   Hossam Ghareeb    11 年前

    我已经为uiview创建了可用的扩展,以便在swift中截图:

    extension UIView{
    
    var screenshot: UIImage{
    
        UIGraphicsBeginImageContext(self.bounds.size);
        let context = UIGraphicsGetCurrentContext();
        self.layer.renderInContext(context)
        let screenShot = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return screenShot
    }
    }
    

    要使用它,只需键入:

    let screenshot = view.screenshot
    
        6
  •  9
  •   Mike Demidov    8 年前

    iOS 10提供了新的API

    extension UIView {
        func makeScreenshot() -> UIImage {
            let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
            return renderer.image { (context) in
                self.layer.render(in: context.cgContext)
            }
        }
    }
    
        7
  •  7
  •   NSResponder    16 年前
    - (void)drawRect:(CGRect)rect {
      UIGraphicsBeginImageContext(self.bounds.size);    
      [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);  
    }
    

    此方法可以放入控制器类中。

        8
  •  5
  •   Matt S.    16 年前
    CGImageRef UIGetScreenImage();
    

    苹果现在允许我们在公共应用程序中使用它,即使它是一个私有的API

        9
  •  4
  •   Michael    14 年前

    苹果不允许:

    CGImageRef UIGetScreenImage();

    应用程序应使用 drawRect 方法见: http://developer.apple.com/library/ios/#qa/qa2010/qa1703.html

        10
  •  4
  •   anthonyqz    10 年前

    我创造了这个 屏幕截图保存扩展 从UIVIEW

    extension UIView {
    func saveImageFromView(path path:String) {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
        drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    
    }}
    

    呼叫 :

    let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
    let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
    reportView.saveImageFromView(path: pathImage)
    

    如果要创建PNG,必须更改:

    UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    

    通过

    UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
    
        11
  •  2
  •   Jayprakash Dubey    12 年前

    以下代码段用于截图:

    UIGraphicsBeginImageContext(self.muUIView.bounds.size);
    
    [myUIView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    使用 renderInContext: 方法而不是 drawInContext: 方法

    渲染上下文: 方法将接收器及其子层呈现到当前上下文中。这种方法 直接从层树渲染。

        12
  •  2
  •   Vasily Bodnarchuk    9 年前

    详细信息

    Xcode 8.2.1,Swift 3

    ui快速查看屏幕截图

    导入uikit 扩展uiview{ var屏幕截图:uiimage?{ uigraphicsBeginImageContextWithOptions(bounds.size,false,1.0); 如果让u=uigraphicsgetcurrentContext()。{ DrawHierarchy(in:bounds,afterscreenupdates:true) 让屏幕截图=uigraphicsGetImageFromCurrentImageContext() uigraphicsEndImageContext()。 返回屏幕截图 } 返回零 } } < /代码>

    使用

    screenshotrenderer.image=viewForscreenshot.screenshot
    

    完整的使用示例

    < Buff行情>

    带uiview扩展名的视图控制器

    < /块引用> 导入uikit 类ViewController:uiViewController{ @屏幕显示:uiview! @iBooklet var屏幕截图趋势器:uiImageView! 重写func viewdidload()。{ super.viewdidload()。 //在加载视图后执行任何其他设置,通常是从NIB加载。 } @IBaction func makeviewscreenshotbuttonApped2(u sender:uibutton){ screenshotrenderer.image=viewForscreenshot.screenshot } } 扩展uiview{ var屏幕截图:uiimage?{ uigraphicsBeginImageContextWithOptions(bounds.size,false,1.0); 如果让u=uigraphicsgetcurrentContext()。{ DrawHierarchy(in:bounds,afterscreenupdates:true) 让屏幕截图=uigraphicsGetImageFromCurrentImageContext() uigraphicsEndImageContext()。 返回屏幕截图 } 返回零 } }
    < Buff行情>
    

    主要。故事板

    < /块引用>
    <?xml version=“1.0”encoding=“utf-8”?gt;
    <document type=“com.apple.interfacebuilder3.cocoatouch.storyboard.xib”version=“3.0”toolsversion=“11762”systemversion=“16c67”targetRuntime=“ios.cocoatouch”propertyaccesscontrol=“none”useautolayout=“yes”usetraitcollections=“yes”colormatched=“yes”initialviewcontroller=“byz-38-t0r”>
    <device id=“retina4_7”orientation=“纵向”>
    <adaptation id=“fullscreen”/>
    &;
    <相关性>
    <deployment identifier=“iOS”/>
    <plugin identifier=“com.apple.interfacebuilder.ibcoatouchplugin”version=“11757”/>
    <capability name=“documents saved in the xcode 8 format”mintoolsversion=“8.0”/>gt;
    </dependencies>
    场景;
    &!--视图控制器-->
    <scene sceneid=“tne qt ifu”>
    对象& gt;
    <viewController id=“byz-38-t0r”customClass=“viewController”customModule=“stackOverflow_2214957”customModuleProvider=“target”scenememberid=“viewController”>
    <布局指南>
    <viewControllerLayoutGuide type=“top”id=“Y3C JY ADJ”/>
    <viewControllerLayoutGuide type=“bottom”id=“wfy db eue”/>
    </layoutguides>
    <view key=“view”contentmode=“scaleToFill”id=“8bc xf vdc”>
    <rect key=“frame”x=“0.0”y=“0.0”width=“375”height=“667”/>gt;
    <autoresizingmask key=“autoresizingmask”widthsizable=“yes”heightsizable=“yes”/>gt;
    <子视图>
    <view contentmode=“scaleToFill”translatesAutoResizingMaskinToConstraints=“no”id=“acg go mmn”>
    <rect key=“frame”x=“67”y=“28”width=“240”height=“128”/>gt;
    <子视图>
    <textfield opaque=“no”clipsSubviews=“yes”contentMode=“scaleToFill”contentHorizontalSignment=“left”contentVerticalAlignment=“center”borderstyle=“roundedRect”textAlignment=“natural”minimumfontsize=“17”translatesAutoResizingMaskingToConstraints=“no”id=“4fr-o3-56t”>
    <rect key=“frame”x=“72”y=“49”width=“96”height=“30”/>gt;
    <限制>
    <constraint firstattribute=“height”constant=“30”id=“clv-es-h7q”/>
    <constraint firstattribute=“width”constant=“96”id=“ytf fh gdm”/>
    </constraints>
    <nil key=“textcolor”/>
    <fontdescription key=“fontdescription”type=“system”pointsize=“14”/>
    <textinputraits key=“textinputraits”/>
    </textfield>
    </Subviews>
    <color key=“backgroundcolor”red=“0.0”green=“0.47843137250000001”blue=“1”alpha=“0.492776113000002”colorspace=“custom”custom colorspace=“srgb”/>
    <color key=“tingcolor”white=“0.666666666666 3”alpha=“1”colorspace=“calibratedwhite”/>gt;
    <限制>
    <constraint firstitem=“4fr-o3-56t”firstattribute=“centerx”seconditem=“acg go mmn”secondattribute=“centerx”id=“egj-rt-gz5”/>gt;
    <constraint firstitem=“4fr-o3-56t”firstattribute=“centery”seconditem=“acg go mmn”secondattribute=“centery”id=“ymi ll wiv”/>gt;
    </constraints>
    &Lt/VIEW & GT;
    <button opaque=“no”contentmode=“scaleToFill”contentHorizontalalignment=“center”contentVerticalAlignment=“center”buttonType=“RoundedRect”linebreakMode=“MiddleTruncation”translatesAutoResizingMaskinToConstraints=“no”id=“sqq ie pvj”>
    <rect key=“frame”x=“109”y=“214”width=“157”height=“30”/>gt;
    <state key=“Normal”title=“生成视图屏幕截图”/>
    <连接>
    <action selector=“MakeViewScreensShotButtonApped2:”destination=“byz-38-t0r”eventtype=“TouchupInside”id=“ksy ec uva”/>gt;
    </connections>
    &按钮/按钮;
    <imageView userInteractionEnabled=“no”contentMode=“scaleAspectFit”horizontalHuggingPriority=“251”verticalHuggingPriority=“251”translatesAutoResizingMaskinToConstraints=“no”id=“cez ju tpq”>
    <rect key=“frame”x=“67”y=“269”width=“240”height=“128”/>gt;
    <限制>
    <constraint firstattribute=“width”constant=“240”id=“sto-ij-rm4”/>
    <constraint firstattribute=“height”constant=“128”id=“tfi zf zdn”/>
    </constraints>
    </imageview>
    </Subviews>
    <color key=“backgroundcolor”red=“0.95941069162436543”green=“0.95941069162436543”blue=“0.95941069162436543”alpha=“1”colorspace=“custom”custom colorspace=“srgb”/>gt;
    <限制>
    <constraint firstitem=“cez ju tpq”firstattribute=“top”seconditem=“sqq ie pvj”secondattribute=“bottom”constant=“25”id=“6x1 ib gkf”/>gt;
    <constraint firstitem=“acg go mmn”firstattribute=“leading”seconditem=“cez ju tpq”secondattribute=“leading”id=“lup be fic”/>gt;
    <constraint firstitem=“sqq ie pvj”firstattribute=“top”seconditem=“acg go mmn”secondattribute=“bottom”constant=“58”id=“qu0-yt-k9o”/>gt;
    <constraint firstitem=“acg go mmn”firstattribute=“centerx”seconditem=“8bc xf vdc”secondattribute=“centerx”id=“qze zd ajy”/>gt;
    <constraint firstitem=“acg go mmn”firstattribute=“trailing”seconditem=“cez ju tpq”secondattribute=“trailing”id=“b1d sp ghd”/>gt;
    <constraint firstitem=“sqq ie pvj”firstattribute=“centerx”seconditem=“cez ju tpq”secondattribute=“centerx”id=“qcl af cro”/>gt;
    <constraint firstitem=“acg go mmn”firstattribute=“top”seconditem=“y3c jy adj”secondattribute=“bottom”constant=“8”symbol=“yes”id=“u5y eh osg”/>
    <constraint firstitem=“cez ju tpq”firstattribute=“centery”seconditem=“8bc xf vdc”secondattribute=“centery”id=“vkx jq pof”/>gt;
    </constraints>
    &Lt/VIEW & GT;
    <连接>
    <outlet property=“screenshotrenderer”destination=“cez ju tpq”id=“8qb-oe-ib6”/>
    <outlet property=“viewForScreenshot”destination=“acg go mmn”id=“jgl-yn-8kk”/>
    </connections>
    </viewcontroller>
    <placeholderIdentifier=“ibFirstResponder”id=“dkx-z0-nzr”scenememberid=“FirstResponder”/>
    </objects>
    <point key=“canvasLocation”x=“32.799999999997”y=“37.331334332833585”/>
    & /场景& GT;
    和/和场景& GT;
    </document>
    < /代码> 
    
    

    结果

    用法

    screenShotRenderer.image = viewForScreenShot.screenShot
    

    _完整的使用示例

    带uiview扩展名的视图控制器

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var viewForScreenShot: UIView!
        @IBOutlet var screenShotRenderer: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        @IBAction func makeViewScreenShotButtonTapped2(_ sender: UIButton) {
            screenShotRenderer.image = viewForScreenShot.screenShot
        }
    }
    
    extension UIView {
    
        var screenShot: UIImage?  {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0);
            if let _ = UIGraphicsGetCurrentContext() {
                drawHierarchy(in: bounds, afterScreenUpdates: true)
                let screenshot = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return screenshot
            }
            return nil
        }
    }
    

    主要故事板

    <?xml version="1.0" encoding="UTF-8"?>
    <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
        <device id="retina4_7" orientation="portrait">
            <adaptation id="fullscreen"/>
        </device>
        <dependencies>
            <deployment identifier="iOS"/>
            <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
            <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
        </dependencies>
        <scenes>
            <!--View Controller-->
            <scene sceneID="tne-QT-ifu">
                <objects>
                    <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_2214957" customModuleProvider="target" sceneMemberID="viewController">
                        <layoutGuides>
                            <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                            <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                        </layoutGuides>
                        <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                            <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                            <subviews>
                                <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Acg-GO-mMN">
                                    <rect key="frame" x="67" y="28" width="240" height="128"/>
                                    <subviews>
                                        <textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="4Fr-O3-56t">
                                            <rect key="frame" x="72" y="49" width="96" height="30"/>
                                            <constraints>
                                                <constraint firstAttribute="height" constant="30" id="cLv-es-h7Q"/>
                                                <constraint firstAttribute="width" constant="96" id="ytF-FH-gdm"/>
                                            </constraints>
                                            <nil key="textColor"/>
                                            <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                            <textInputTraits key="textInputTraits"/>
                                        </textField>
                                    </subviews>
                                    <color key="backgroundColor" red="0.0" green="0.47843137250000001" blue="1" alpha="0.49277611300000002" colorSpace="custom" customColorSpace="sRGB"/>
                                    <color key="tintColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                                    <constraints>
                                        <constraint firstItem="4Fr-O3-56t" firstAttribute="centerX" secondItem="Acg-GO-mMN" secondAttribute="centerX" id="egj-rT-Gz5"/>
                                        <constraint firstItem="4Fr-O3-56t" firstAttribute="centerY" secondItem="Acg-GO-mMN" secondAttribute="centerY" id="ymi-Ll-WIV"/>
                                    </constraints>
                                </view>
                                <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="SQq-IE-pvj">
                                    <rect key="frame" x="109" y="214" width="157" height="30"/>
                                    <state key="normal" title="make view screen shot"/>
                                    <connections>
                                        <action selector="makeViewScreenShotButtonTapped2:" destination="BYZ-38-t0r" eventType="touchUpInside" id="KSY-ec-uvA"/>
                                    </connections>
                                </button>
                                <imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="CEZ-Ju-Tpq">
                                    <rect key="frame" x="67" y="269" width="240" height="128"/>
                                    <constraints>
                                        <constraint firstAttribute="width" constant="240" id="STo-iJ-rM4"/>
                                        <constraint firstAttribute="height" constant="128" id="tfi-zF-zdn"/>
                                    </constraints>
                                </imageView>
                            </subviews>
                            <color key="backgroundColor" red="0.95941069162436543" green="0.95941069162436543" blue="0.95941069162436543" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                            <constraints>
                                <constraint firstItem="CEZ-Ju-Tpq" firstAttribute="top" secondItem="SQq-IE-pvj" secondAttribute="bottom" constant="25" id="6x1-iB-gKF"/>
                                <constraint firstItem="Acg-GO-mMN" firstAttribute="leading" secondItem="CEZ-Ju-Tpq" secondAttribute="leading" id="LUp-Be-FiC"/>
                                <constraint firstItem="SQq-IE-pvj" firstAttribute="top" secondItem="Acg-GO-mMN" secondAttribute="bottom" constant="58" id="Qu0-YT-k9O"/>
                                <constraint firstItem="Acg-GO-mMN" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="Qze-zd-ajY"/>
                                <constraint firstItem="Acg-GO-mMN" firstAttribute="trailing" secondItem="CEZ-Ju-Tpq" secondAttribute="trailing" id="b1d-sp-GHD"/>
                                <constraint firstItem="SQq-IE-pvj" firstAttribute="centerX" secondItem="CEZ-Ju-Tpq" secondAttribute="centerX" id="qCL-AF-Cro"/>
                                <constraint firstItem="Acg-GO-mMN" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="u5Y-eh-oSG"/>
                                <constraint firstItem="CEZ-Ju-Tpq" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="vkx-JQ-pOF"/>
                            </constraints>
                        </view>
                        <connections>
                            <outlet property="screenShotRenderer" destination="CEZ-Ju-Tpq" id="8QB-OE-ib6"/>
                            <outlet property="viewForScreenShot" destination="Acg-GO-mMN" id="jgL-yn-8kk"/>
                        </connections>
                    </viewController>
                    <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
                </objects>
                <point key="canvasLocation" x="32.799999999999997" y="37.331334332833585"/>
            </scene>
        </scenes>
    </document>
    

    结果

    enter image description here enter image description here

        13
  •  1
  •   JMarsh    12 年前
    -(UIImage *)convertViewToImage
    {
        UIGraphicsBeginImageContext(self.bounds.size);
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
      return image;
    }
    
        14
  •  1
  •   Ankit Kumar Gupta    7 年前

    Swift 4更新:

    extension UIView {
       var screenShot: UIImage?  {
            if #available(iOS 10, *) {
                let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
                return renderer.image { (context) in
                    self.layer.render(in: context.cgContext)
                }
            } else {
                UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5);
                if let _ = UIGraphicsGetCurrentContext() {
                    drawHierarchy(in: bounds, afterScreenUpdates: true)
                    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()
                    return screenshot
                }
                return nil
            }
        }
    }
    
        15
  •  0
  •   Shree Krishna    10 年前

    您可以使用以下uiview类别-

    @implementation UIView (SnapShot)
    
     - (UIImage *)snapshotImage
    {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);        
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];        
        // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();        
        UIGraphicsEndImageContext();        
        return image;
    }    
    @end
    
    推荐文章