ios - 切り抜いた円でUIViewをマスクする
calayer properties (2)
私は、半透明の黒い背景を持つUIView
を作成して、メインアプリケーションのビュー全体に座っています。 私がここで目指しているのは、半透明の黒色の背景が見えないUIView
どこかに切り抜き円の形を作成し、円形の領域を除く画像全体に黒いマスクの効果を与えることです(これはその領域のボタンをハイライト表示します)。
私は円形マスクを作成するためにCAShapeLayer
を使用することにCAShapeLayer
しましたが、これは逆の効果がありました(つまり、ビューの残りの部分はクリアで、円の内側は半透明の黒です。半透明の黒を維持するための円、次に内側の透明点を指定します。ここで使用したコードは、逆の方法でどのように動作させるのですか?私のblackMask
は半透明の黒いビューで、 buttonCircle
は私は明確にしたいと思います。
おそらく、私は何とか経路を逆転させる必要がありますか?
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
CGRect maskRect = buttonCircle.frame;
CGPathRef path = CGPathCreateWithEllipseInRect(maskRect, NULL);
maskLayer.path = path;
CGPathRelease(path);
blackMask.layer.mask = maskLayer;
編集:今これを試して、これですべてのマスクを見ていない:
UIView *circularMaskView = [[UIView alloc] initWithFrame:buttonCircle.frame];
circularMaskView.backgroundColor = [UIColor greenColor];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
CGPathRef path = CGPathCreateWithEllipseInRect(buttonCircle.frame, NULL);
maskLayer.path = path;
CGPathRelease(path);
circularMaskView.layer.mask = maskLayer;
[blackMask addSubview:circularMaskView];
ブラック画像を使用してマスクしている場合
-(void)maskWithImage:(UIImage*)maskImage toImageView:(UIImageView*)imgView{
CALayer *aMaskLayer=[CALayer layer];
aMaskLayer.contents=(id)maskImage.CGImage;
imgView.layer.mask=aMaskLayer;
}
マスクするカスタムシェイプレイヤがある場合
-(void)maskWithShapeLayer:(CALayer*)layer toImageView:(UIImageView*)imgView{
//Layer should be filled with Black color to mask those part of Image
imgView.layer.mask=layer;
}
イメージビューマスクを円で作成したい場合
-(void)maskWithCircle:(UIImageView*)imgView{
CAShapeLayer *aCircle=[CAShapeLayer layer];
aCircle.path=[UIBezierPath bezierPathWithRoundedRect:imgView.bounds cornerRadius:imgView.frame.size.height/2].CGPath; // Considering the ImageView is square in Shape
aCircle.fillColor=[UIColor blackColor].CGColor;
imgView.layer.mask=aCircle;
}
それでは、私がしたことがここにあります。 BlackoutView
というカスタムUIView
サブクラスを作成しました。
BlackoutView.h
#import <UIKit/UIKit.h>
@interface BlackoutView : UIView
@property (nonatomic, retain) UIColor *fillColor;
@property (nonatomic, retain) NSArray *framesToCutOut;
@end
BlackoutView.m
#import "BlackoutView.h"
@implementation BlackoutView
- (void)drawRect:(CGRect)rect
{
[self.fillColor setFill];
UIRectFill(rect);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
for (NSValue *value in self.framesToCutOut) {
CGRect pathRect = [value CGRectValue];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:pathRect];
[path fill];
}
CGContextSetBlendMode(context, kCGBlendModeNormal);
}
@end
次に、通常のようにインスタンス化し、使用するマスクの色とマスクから切り取るフレームのプロパティを設定します。
[blackMask setFillColor:[UIColor colorWithWhite:0.0f alpha:0.8f]];
[blackMask setFramesToCutOut:@[[NSValue valueWithCGRect:buttonCircleA.frame],
[NSValue valueWithCGRect:buttonCircleB.frame]]];
これは、私が楕円以外の他の形を切り取れるようにすることで改善することができますが、ここでの目的はうまくいき、後で簡単に適用できます。 うまくいけば、これは他の人に役立ちます