繁体   English   中英

从UIView捕获UIImage无法正常工作

[英]Capture UIImage from UIView not working

我正在尝试使用imagecontext从UIView捕获UIImage

func captureImage() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0.0)
    self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img
}

我也尝试过使用renderinContext()

我在UIViewextension中有这个

我用它来从MapBoxView获取图像,它是UIView的子类。

if let viewImage = self.mapView?.resizableSnapshotViewFromRect(frame, afterScreenUpdates: false, withCapInsets: UIEdgeInsetsZero) {
    let img = viewImage.captureImage()

    self.view.addSubview(UIImageView(image: img))
}

captureImage()函数返回的img只是黑色的...

当我将viewImage添加到视图中时, viewImage具有正确的内容,因此Capture方法有问题。

resizableSnapshotViewFromRect返回UIView对象,但是您无需将此对象添加到视图层次结构中,也不显示此视图。 因此,在这种情况下, self.drawViewHierarchyInRect不会绘制任何内容。

为什么不直接从mapView捕获UIImage?

if let img = self.mapView?.captureImage() {
    self.view.addSubview(UIImageView(image: img))
}

要从MapView获取快照,您还可以使用MKMapSnapshotter类的帮助。

请参阅以下内容:

func takeSnapShot {

    var options = MKMapSnapshotOptions()
    options.region = self.mapView.region
    options.scale = UIScreen.mainScreen().scale

    var snapshotter = MKMapSnapshotter(options: options)
    snapshotter .startWithCompletionHandler { (var snapShot: MKMapSnapshot!, var error: NSError!) -> Void in
        var image = snapShot.image as UIImage!
    }
}

编辑:

我浏览了MapBox RMMapView ,发现有一种从地图上拍摄快照的方法。

- (UIImage *)takeSnapshot;

是的,您可以从地图的特定部分进行捕捉。 MKMapSnapshotOptions类具有属性size ,您可以在上面的代码中传递所需的大小。

func takeSnapShot {

    var options = MKMapSnapshotOptions()
    options.region = self.mapView.region
    options.scale = UIScreen.mainScreen().scale

    // The size of the image to create. Defaults to 256x256
    options.size = CGSizeMake(100, 100);

    var snapshotter = MKMapSnapshotter(options: options)
    snapshotter .startWithCompletionHandler { (var snapShot: MKMapSnapshot!, var error: NSError!) -> Void in
        var image = snapShot.image as UIImage!
    }
}

将OS_VERSION的宏定义为:

#define OS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]

要获取任何视图的快照图像,可以使用以下方法:

- (UIImage *)takeSnapshotOfView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);

    if (OS_VERSION < 7.0)
    {
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    else
    {
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    }

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

    return snapshot;
}

如果您有任何疑问,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM