objective-c – 在Cocoa中将视图层次结构绘制到特定上下文中

objective-c – 在Cocoa中将视图层次结构绘制到特定上下文中,第1张

概述对于我的部分应用程序,我需要创建某个视图及其所有子视图的图像. 为此,我创建了一个包含与视图大小相同的位图的上下文,但我不确定如何将视图层次结构绘制到其中.我可以绘制单个视图,只需设置上下文并显式调用drawRect,但这不会处理所有子视图. 我无法在NSView界面中看到任何可以帮助解决此问题的内容,因此我怀疑解决方案可能处于更高级别. 我发现自己编写绘图代码是最好的方法: >处理潜在的透明度问 对于我的部分应用程序,我需要创建某个视图及其所有子视图的图像.

为此,我创建了一个包含与视图大小相同的位图的上下文,但我不确定如何将视图层次结构绘制到其中.我可以绘制单个视图,只需设置上下文并显式调用drawRect,但这不会处理所有子视图.

我无法在NSVIEw界面中看到任何可以帮助解决此问题的内容,因此我怀疑解决方案可能处于更高级别.

解决方法 我发现自己编写绘图代码是最好的方法:

>处理潜在的透明度问题(其他一些选项确实为整个图像添加了白色背景)
>表现要好得多

下面的代码并不完美,因为它不处理从边界到帧的扩展问题,但它确实考虑了isFlipped状态,并且非常适合我使用它.请注意,它只绘制子视图(和子视图,…递归),但让它自己绘制也很容易,只需在imageWithSubvIEws的实现中添加[self drawRect:[self bounds]].

- (voID)drawSubvIEws{    BOol flipped = [self isFlipped];    for ( NSVIEw *subvIEw in [self subvIEws] ) {        // changes the coordinate system so that the local coordinates of the subvIEw (bounds) become the coordinates of the supervIEw (frame)        // the transform assumes bounds and frame have the same size,and bounds origin is (0,0)        // handling of 'isFlipped' also probably unreliable        NSAffinetransform *transform = [NSAffinetransform transform];        if ( flipped ) {            [transform translateXBy:subvIEw.frame.origin.x yBy:NSMaxY(subvIEw.frame)];            [transform scaleXBy:+1.0 yBy:-1.0];        } else            [transform translateXBy:subvIEw.frame.origin.x yBy:subvIEw.frame.origin.y];        [transform concat];        // recursively draw the subvIEw and sub-subvIEws        [subvIEw drawRect:[subvIEw bounds]];        [subvIEw drawSubvIEws];        // reset the transform to get back a clean graphic contexts for the rest of the drawing        [transform invert];        [transform concat];    }}- (NSImage *)imageWithSubvIEws{    NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];    [image lockFocus];    // it seems NSImage cannot use flipped coordinates the way NSVIEw does (the method 'setFlipped:' does not seem to help)    // Use instead an NSAffinetransform    if ( [self isFlipped] ) {        NSAffinetransform *transform = [NSAffinetransform transform];        [transform translateXBy:0 yBy:NSMaxY(self.bounds)];        [transform scaleXBy:+1.0 yBy:-1.0];        [transform concat];    }    [self drawSubvIEws];    [image unlockFocus];    return image;}
总结

以上是内存溢出为你收集整理的objective-c – 在Cocoa中将视图层次结构绘制到特定上下文中全部内容,希望文章能够帮你解决objective-c – 在Cocoa中将视图层次结构绘制到特定上下文中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1003603.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存