xcode 在 iOS 中使用混合模式堆叠 UIViews

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14148973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:27:39  来源:igfitidea点击:

Stacking UIViews with blend modes in iOS

objective-ciosxcodeuiviewcalayer

提问by Kurt Revis

I have two different UIImageViews. I'd like to make the top UIImageViewblend in using the Screen blend mode with the bottom UIImageView.

我有两个不同的UIImageViews。我想将顶部UIImageView与底部混合使用屏幕混合模式UIImageView

I know of the property of CALayer: compositingFilterand I know that it doesn't work in iOS. I've searched a lot for solutions, and I've found how one should subclass UIViewand override drawRect.

我知道的财产CALayercompositingFilter我知道它不会在iOS的工作。我已经搜索了很多解决方案,我发现应该如何子类化UIView和覆盖drawRect.

I've tried to set the context in drawRectto the screen blend mode, although it still draws every one of the images normally. Perhaps I am doing something wrong, or the approach should be different. Maybe I need OpenGL or CALayer to achieve this. Could someone assist?

我已经尝试将上下文设置为drawRect屏幕混合模式,尽管它仍然正常绘制每一幅图像。也许我做错了什么,或者方法应该不同。也许我需要 OpenGL 或 CALayer 来实现这一点。有人可以帮忙吗?

回答by Kurt Revis

Unfortunately there is no way to do a non-composite blend between UIViews on iOS. UIKit doesn't provide the functionality, and you've already noted, CALayer can't do it either.

不幸的是,无法在 iOS 上的 UIViews 之间进行非复合混合。UIKit 不提供该功能,您已经注意到,CALayer 也无法提供。

In general, implementing -drawRect in a UIView won't help you. You're drawing into an empty bitmap -- it doesn't contain the bits of the views behind it, since those might change at any time (any view or layer might be animated). CA fundamentally assumes that layers' contents should be independent of each other.

一般来说,在 UIView 中实现 -drawRect 不会帮助你。您正在绘制一个空位图 - 它不包含其背后的视图位,因为这些位可能随时更改(任何视图或图层都可能被动画化)。CA 从根本上假设层的内容应该相互独立。

You couldtry, in your -drawRect:

可以试试,在你的-drawRect:

  1. create an image context
  2. capture the views under your view using -[CALayer renderInContext:]for each
  3. create an image from the image context
  4. draw that image into your view
  5. set the blend mode and draw on top of that
  1. 创建图像上下文
  2. 使用-[CALayer renderInContext:]for each捕获视图下的视图
  3. 从图像上下文创建图像
  4. 将该图像绘制到您的视图中
  5. 设置混合模式并在其上绘制

But that will be slow and fragile, and won't work if you animate any of the views. I wouldn't recommend it.

但这将是缓慢而脆弱的,并且如果您为任何视图设置动画就行不通。我不会推荐它。

If you really need to do this, you're going to have to switch your whole scene to render with OpenGL, where you've got more freedom.

如果您真的需要这样做,您将不得不将整个场景切换为使用 OpenGL 进行渲染,这样您就有更多的自由