23

UIView的opaque属性默认始终设置为“YES”。但是 UIView 类参考说明了这一点:

一个不透明的视图应该用完全不透明的内容填充它的边界——也就是说,内容的 alpha 值应该是 1.0。如果视图是不透明的并且没有填充其边界或包含完全或部分透明的内容,则结果是不可预测的。

由于更改alpha视图的属性非常普遍,尤其是在过渡或动画期间,因此上述声明暗示如果您要更改属性,则必须始终手动设置为opaqueNOalpha

但是我从来没有手动调整过opaque,也没有任何明显的症状。做这个考虑有多大必要?

4

2 回答 2

16

The answer is that iOS is smart enough to recognize that if your view's alpha is less than 1, it needs to draw the content behind your view, regardless of your view's opaque property.

In response to comments: from my limited experimentation, I don't think the view's opaque property has any effect. (I think the documentation is wrong.) The view's layer's opaque property does have an effect: it controls whether the CGContext passed to drawRect: has an alpha channel. If the layer's opaque property is YES, the context has no alpha channel (and is treated as if every pixel has alpha of 1.0).

Changing the view's opaque property has no effect on the layer's opaque property. This is different than (for example) the view's alpha property, which is just a wrapper for the layer's opacity property.

In theory, having documented that the opaque property allows them to optimize drawing, Apple could implement that optimization in the future. In practice, doing so would probably break a lot of apps, so they probably won't make such a change apply to apps linked against older SDKs. (They have the ability to make UIKit behave differently depending on which version the app was linked with.)

于 2012-05-04T07:18:31.450 回答
1

As long as the view contents itself (not its subviews) don't have alpha you're fine. So if you init an UIImageViews with an PNG image with alpha, opaque will be set to NO automatically.

Normally you don't really need many non-opaque views. But alpha of the complete view is smth different anyway.

于 2012-05-04T07:21:13.140 回答