0

I’m overlaying two UIViews with a white backgroundColor at 25% opacity. In a small part, they overlap each other, meaning that at that area, they are summed to 50% opacity.

I’d like to keep that 25% opacity, even if the two views overlap, effectively meaning that in those overlapped points, each view’s opacity drops to 12.5% to total 25%.

I’ve done a little looking into compositing but I’m not sure which of these modes would help, or how I’d go about applying them to a specific part of these two UIView instances.

(http://docs.oracle.com/javase/tutorial/2d/advanced/compositing.html is what I was reading, and I found the CGBlendMode for drawing, if it comes to using that (though I’d prefer not to if possible!))

4

2 回答 2

1

如果您将它们都添加到同一个 parent UIView,告诉它UIView进行光栅化,然后在父级上设置 alpha,您将获得所需的效果。我不确定这是否符合您的显示结构或性能需求。

UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[parent setBackgroundColor:[UIColor clearColor]];
[parent.layer setShouldRasterize:YES];
[parent.layer setRasterizationScale:[[UIScreen mainScreen] scale]];
[parent setAlpha:0.25];
UIView *subview1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 125, 125)];
[subview1 setBackgroundColor:[UIColor whiteColor]];
[parent addSubview:subview1];
UIView *subview2 = [[UIView alloc] initWithFrame:CGRectMake(75, 75, 125, 125)];
[subview2 setBackgroundColor:[UIColor whiteColor]];
[parent addSubview:subview2];
于 2014-10-14T15:44:25.920 回答
1

您无法控制CALayeriOS 上视图(或者,实际上是 s)的合成模式。

我能想到的最好的解决方案是让两个视图都带有clearColor(或nil)背景,并使用一个CAShapeLayer来绘制两者的背景。如果您的两个视图具有相同的父级,那并不太难。

假设父母是 type ParentView。根据需要覆盖layoutSubviewsParentView创建和更新背景层。如果您移动任何一个子视图,请务必发送setNeedsLayout到父视图。

ParentView.h

#import <UIKit/UIKit.h>

@interface ParentView : UIView

@property (nonatomic, strong) IBOutlet UIView *childView0;
@property (nonatomic, strong) IBOutlet UIView *childView1;

@end

ParentView.m

#import "ParentView.h"

@implementation ParentView {
    CAShapeLayer *backdrop;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self layoutBackdrop];
}

- (void)layoutBackdrop {
    [self createBackdropIfNeeded];
    [self arrangeBackdropBehindChildren];
    [self setBackdropPath];
}

- (void)createBackdropIfNeeded {
    if (backdrop == nil) {
        backdrop = [CAShapeLayer layer];
        backdrop.fillColor = [UIColor colorWithWhite:1 alpha:0.25].CGColor;
        backdrop.fillRule = kCAFillRuleNonZero;
        backdrop.strokeColor = nil;
    }
}

- (void)arrangeBackdropBehindChildren {
    [self.layer insertSublayer:backdrop atIndex:0];
}

- (void)setBackdropPath {
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.childView0.frame];
    [path appendPath:[UIBezierPath bezierPathWithRect:self.childView1.frame]];
    backdrop.path = path.CGPath;
}

@end
于 2014-10-14T15:55:50.073 回答