2

我想编写一个 UIView 子类,除其他外,将其下方的任何内容着色为某种颜色。这是我想出的,但不幸的是它似乎无法正常工作:

#import <UIKit/UIKit.h>

@class MyOtherView;
@interface MyView : UIView
{
    MyOtherView *subview;
}
@end

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        frame.origin.x += 100.0;
        frame.origin.y += 100.0;
        frame.size.width = frame.size.height = 200.0;
        subview = [[MyOtherView alloc] initWithFrame:frame];
        [self addSubview:subview];
        [subview release];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    // Draw a background to test out on
    UIImage *image = [UIImage imageNamed:@"somepic.png"];
    [image drawAtPoint:rect.origin];

    const CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blueColor] setFill];
    rect.size.width = rect.size.height = 200.0;
    CGContextFillRect(ctx, rect);
}

@end

@interface MyOtherView : UIView
@end

@implementation MyOtherView

- (void)drawRect:(CGRect)rect
{
    // This should tint "MyView" but it doesn't.
    const CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGContextSetBlendMode(ctx, kCGBlendModeScreen);
    [[UIColor redColor] setFill];
    CGContextFillRect(ctx, rect);
    CGContextRestoreGState(ctx);
}

@end

我希望“MyOtherView”在它重叠的地方将“MyView”涂成红色,但它只是在上面绘制一个不透明的红色块。但是,如果我从“MyOtherView”复制 -drawRect: 函数并将其附加到“MyView”中的函数,这似乎可以正常工作(这让我很头疼最终意识到)。有人知道我在做什么错吗?甚至有可能做到这一点,还是我应该以不同的方式接近它?

4

2 回答 2

0

我觉得你想多了。将一个视图覆盖在另一个视图上,并将顶视图的 alpha 设置为 0.5。您还需要将 opaque 设置为 NO。

如果您适当地设置视图的背景颜色,您甚至不需要覆盖 drawRect。

于 2009-08-17T06:09:08.143 回答
0

可能想看看这个 SO question

于 2009-08-17T06:14:01.393 回答