如何让iPhone上的部分屏幕显示子视图?

时间:2009-08-17 05:41:11

标签: iphone objective-c cocoa-touch quartz-graphics

我想编写一个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”中的那个函数,这似乎工作正常(这让我终于意识到这让我很头疼)。谁知道我做错了什么?甚至可以这样做,还是我应该以不同的方式接近它?

2 个答案:

答案 0 :(得分:0)

我认为你过分思考这个问题。将一个视图叠加在另一个视图上,并将顶视图的alpha设置为0.5。您还需要将opaque设置为NO。

如果您正确设置了视图的背景颜色,则甚至不需要覆盖drawRect。

答案 1 :(得分:0)

可能想查看this SO question