简体   繁体   English

更改一小部分的UIView的颜色?

[英]Changing color of small portion of UIView?

I have a UIView whose color is black and opacity is 0.9 or something like that. 我有一个UIView其颜色为黑色,不透明度为0.9或类似的值。 What I want to do is to fill the UIView with black portion, but a specified rectangular area should not get black. 我想做的是用黑色部分填充UIView ,但是指定的矩形区域不应变黑。 ie that particular rectangular area remains with clear color... 也就是说,特定的矩形区域仍然具有清晰的颜色...

Any kind of help will be appreciated. 任何帮助将不胜感激。

regards, 问候,

Imran 伊姆兰

You can subclass UIView and override - (void)drawRect:(CGRect)rect 您可以- (void)drawRect:(CGRect)rect UIView并重写- (void)drawRect:(CGRect)rect

And do something of the following (untested, but used something similar myself); 然后执行以下操作(未经测试,但自己使用了类似的方法);

- (void)drawRect:(CGRect)rect {

// fill the whole UIView with a color
[[UIColor colorWithRed:1 green:1 blue:1 0.9] setFill];
UIRectFill( rect );

// draw a rect
CGRect rectIntersection = CGRectIntersection(theRectIWantToDrawIn, rect);

[[UIColor clearColor] setFill];
UIRectFill( rectIntersection );
}

The code above draws a black view with a simulated clearColor hole in it at a certain position. 上面的代码在特定位置绘制了一个带有模拟clearColor孔的黑色视图。 You could, of course, alter this behavior to your liking. 当然,您可以根据自己的喜好更改此行为。

This is quite fast. 这是相当快的。

UPDATE: Do note that I set the UIView on which I want to draw the rect to UIClear color (I added it to a xib and set those properties there) and unchecked 'Opaque'. 更新:请注意,我将要在其上绘制矩形的UIView设置为UIClear颜色(我将其添加到xib并在那里设置了那些属性),并且未选中“不透明”。 That should make the hole see-through. 那应该使孔透明。

UPDATE 2: My answer was based on this answer (credit where credit is due): iPhone - Draw transparent rectangle on UIView to reveal view beneath 更新2:我的答案是基于以下答案(应归功于贷方): iPhone-在UIView上绘制透明矩形以显示下面的视图

Add another view (subview) to that area. 在该区域添加另一个视图(子视图)。 And set its to your desired color. 并将其设置为您想要的颜色。 Thats the easy solution with your current requirements. 满足您当前需求的简单解决方案。 Or you can use some quartz core functions. 或者,您可以使用一些石英芯功能。

You can create a small UIView in the main view by custom and set background clear color 您可以通过自定义在主视图中创建一个小的UIView并设置背景透明色

UIView *View1 = [[UIView alloc] initWithFrame:CGRectMake(128.0f, 50.0f, 34.0f, 34.0f)];
[View1 setBackgroundColor:[UIColor clearColor]];        
[self.view addSubview:View1];
[View1 release];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM