3

を色でUIButtonオーバーレイしようとすると、この問題が発生します。Image

オーバーレイの色が の下に表示されImageます。

メソッドにあるコードは次のとおりですdrawRect(サブクラス化しましたUIButton):

(void)drawRect:(CGRect)rect
{
    CGRect bounds = self.imageView.bounds;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    CGContextTranslateCTM(context, 0.0, self.imageView.image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextClipToMask(context, bounds, [self.imageView.image CGImage]);
    CGContextFillRect(context, bounds);
}

の上に赤い色を付ける方法についてのアイデアはありImageますか?

4

1 に答える 1

2

このハッキーなコードで成功しました:

- (void)drawRect:(CGRect)rect
{
    UIImage* img = [self imageForState:UIControlStateNormal];
    [self setImage:nil forState:UIControlStateNormal];
    CGRect bounds = self.imageView.bounds;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2].CGColor);
    CGContextDrawImage(context, bounds, img.CGImage);
    CGContextFillRect(context, bounds);
}

画像は drawRect の後に描画されるように見えるので、nil にしない限り、そこに描画したものの上に表示されます。

これは最終的な解決策ではありません。私は次に得るものでそれを編集します。

編集: 正しい解決策は、次のように画像の上に半透明の UIView を追加することです。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIView* tintView = [[UIView alloc] initWithFrame:self.bounds];
        tintView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2];
        tintView.userInteractionEnabled = NO;
        [self addSubview:tintView];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIView* tintView = [[UIView alloc] initWithFrame:self.bounds];
        tintView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2];
        tintView.userInteractionEnabled = NO;
        [self addSubview:tintView];
    }
    return self;
}

注: UIButton サブクラスでこれを行う必要があります。

于 2012-12-26T18:16:41.217 に答える