現在請け負っているiOSアプリで、画像のトリミング用ガイドとして
画像の上に切り抜く部分のみ透過しているマスクを作る必要があったんですが、
ほとんど情報がなかったのでメモ。
こちらに希望するものがあったのですがSwiftのソースで、
今回Objective-Cで組んでいたのでObjective-Cに書き直してみました。
(今さら、こんなダウンコンバートしたの必要な人いるかな。。。)
オートレイアウトを考えると、画像で作るよりソースで作成できたほうがいいですね。
UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.view.size.width, self.view.frame.size.height)];
// くりぬき元レイヤー
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.7f].CGColor;
layer.bounds = CGRectMake(0, 0, (maskView.frame.size.width), (maskView.frame.size.height));
layer.position = CGPointMake( (maskView.frame.size.width/2), (maskView.frame.size.height/2) );
// マスクレイヤー
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.bounds = CGRectMake(0, 0, (maskView.frame.size.width), (maskView.frame.size.height));
// 切り抜くサイズでパスを作る
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(20, (maskView.frame.size.height/2-100), (maskView.frame.size.width-40), 200)];
[path appendPath:[UIBezierPath bezierPathWithRect:maskLayer.bounds]];
// 反転させるため、くりぬき元レイヤーと同じ色を設定
maskLayer.fillColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.7f].CGColor;
maskLayer.path = path.CGPath;
maskLayer.position = CGPointMake( (maskView.frame.size.width/2), (maskView.frame.size.height/2) );
// マスクのルールをeven/oddに設定する
maskLayer.fillRule = kCAFillRuleEvenOdd;
layer.mask = maskLayer;
[maskView.layer addSublayer:layer];
[self.view addSubView:maskView];
