可可:如何渲染视图到图像? [英] cocoa: how to render view to image?

查看:130
本文介绍了可可:如何渲染视图到图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法来呈现视图的图像?就像一个截图,但我可以指定任何视图的方法。我知道如何做在ios。 保存查看内容,但是如何在mac os中做呢?

I want to know is there any method to render a view to image? just like a screenshot, but I can specify any view to that method. I know how to do it in ios. Saving view content, but how can I do it in mac os ?

推荐答案

有几种方法,工作完美。
许多问题都与Layer Backed视图相关联。

There are several ways, but non of them works perfect. Many problems are connected with Layer Backed views.

如果没有图层备份或托管视图,您可以使用此代码:

if you don't have layer backing or hosting views you can use this code:

    NSData* data = [mainView dataWithPDFInsideRect:[mainView bounds]];
    NSImage *img = [[NSImage alloc] initWithData:data];

到10.8对我来说最好的方法是

till 10.8 the best way for me was

        NSSize mySize = mapImage.bounds.size;
        NSSize imgSize = NSMakeSize( mySize.width, mySize.height );
        NSBitmapImageRep *bir = [mapImage bitmapImageRepForCachingDisplayInRect:[mapImage bounds]];
        [bir setSize:imgSize];
        [mapImage cacheDisplayInRect:[mapImage bounds] toBitmapImageRep:bir];
        caheImg = [[NSImage alloc]initWithSize:imgSize];
        [caheImg addRepresentation:bir];

但在10.8 bitmapImageRepForCachingDisplayInRect 已备份的视图。

but in 10.8 bitmapImageRepForCachingDisplayInRect stopped working with Layer Backed views.

有一个选项用于截取屏幕截图并剪下您的视图:

there is an option to make a screenshot of your screen and cut out your view:

+ (NSImage*) screenCacheImageForView:(NSView*)aView
{
    NSRect originRect = [aView convertRect:[aView bounds] toView:[[aView window] contentView]];

    NSRect rect = originRect;
    rect.origin.y = 0;
    rect.origin.x += [aView window].frame.origin.x;
    rect.origin.y += [[aView window] screen].frame.size.height - [aView window].frame.origin.y - [aView window].frame.size.height;
    rect.origin.y += [aView window].frame.size.height - originRect.origin.y - originRect.size.height;

    CGImageRef cgimg = CGWindowListCreateImage(rect,
                                           kCGWindowListOptionIncludingWindow,
                                           (CGWindowID)[[aView window] windowNumber],
                                           kCGWindowImageDefault);
    return [[NSImage alloc] initWithCGImage:cgimg size:[aView bounds].size];
}

这篇关于可可:如何渲染视图到图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆