gpt4 book ai didi

ios - 在 iOS 中绘制一个半透明的矩形

转载 作者:可可西里 更新时间:2023-11-01 04:30:19 25 4
gpt4 key购买 nike

我一直在寻找答案,也试图自己解决,但我做不到,我认为这是最好的提问地点。所以我试图完成一些简单的事情,但我就是找不到方法。我想我在概念层面上遗漏了一些东西。这就是我尝试在子类化 UIView 的类中创建半透明矩形的方式:

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//this should be white color with 0.7 opacity right
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.7);
CGContextFillRect(context, self.bounds);
}

好的,这只会使颜色变灰。我也试过这个但结果相同: CGContextSetRGBFillColor(上下文, 1.0, 1.0, 1.0, 1.0);
CGContextSetAlpha(上下文, 0.7);

另一个尝试:

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(context, self.bounds);

self.alpha = 0.7;
}

瞧!我解决了。但不完全是。我想在上下文中绘制一个半透明的矩形而不是使整个 View 透明。然后例如添加另一个完全不透明的矩形。很想听听你的想法。谢谢。

最佳答案

我猜你看不到矩形透明度的原因是 View 中存在背景色。

你会尝试像这样设置 View 背景颜色吗:

self.backgroundColor = [UIColor clearColor];

顺便说一句,这条语句以及任何设置自定义 View 属性的语句(例如,self.alpha = 0.7;)都应该进入 init 方法.

编辑:

正如@borrrden 所指出的,为了实现这一目的而设置的真实属性可能是opaque。根据 Apple Docs,这通常设置为 YES,因此暗示以下内容:

An opaque view is expected to fill its bounds with entirely opaque content—that is, the content should have an alpha value of 1.0. If the view is opaque and either does not fill its bounds or contains wholly or partially transparent content, the results are unpredictable. You should always set the value of this property to NO if the view is fully or partially transparent.

将背景颜色设置为 clearColor 可能会将此属性的值设置为 NO 作为附带效果。

编辑:

我不明白你为什么要覆盖自定义 UIView 中的 drawRect 来绘制一个半透明的矩形,可能是因为我不知道你在做什么.在任何情况下,您可能想要研究的另一种方法是使用嵌套的 UIViews 或嵌套的 CALayers,您可以在其中分配不同的 alpha/opacity 给它们中的任何一个。

如果您只对具有不同程度不透明度的矩形感兴趣,这就像在父 View 中嵌套 UIViews 并为每个 View 分配半透明背景色一样简单。

关于ios - 在 iOS 中绘制一个半透明的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19219371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com