我想知道如何在 UIView 中剪出一条路径。
这是我的问题的简要说明-
我有两个 UIView
s,一个带有红色,另一个带有绿色背景色。
绿色的在红色的上面。
因此,如果用户在绿色 UIView
中触摸并移动他的手指,他的触摸位置应该从那个UIView
中删掉。和红色UIView
从那个区域应该是可见的。
这是一张可以轻松描述问题的图像 -
Visual description
我知道如何获取用户的手指触摸位置,但不知道如何从 UIView
中切出路径.
请帮忙。
最佳答案
我只使用 1 个 View 。你也可以做到的。
迅速:
import UIKit
class PanView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
_init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_init()
}
func _init() {
layer.backgroundColor = UIColor.greenColor().CGColor
let green = CALayer()
green.frame = layer.bounds
green.backgroundColor = UIColor.redColor().CGColor
layer.addSublayer(green)
let mask = CAShapeLayer()
mask.frame = green.bounds
mask.strokeColor = UIColor.whiteColor().CGColor
mask.fillColor = UIColor.clearColor().CGColor
mask.lineWidth = 10
mask.lineJoin = kCALineJoinRound
let path = UIBezierPath()
mask.path = path.CGPath
green.mask = mask
let pan = UIPanGestureRecognizer(target: self, action: "pan:")
addGestureRecognizer(pan)
}
func pan(pan: UIPanGestureRecognizer) {
let p = pan.locationInView(self)
if let mask = layer.sublayers?.first?.mask as? CAShapeLayer, path = mask.path {
let path = UIBezierPath(CGPath: path)
if pan.state == UIGestureRecognizerState.Began {
path.moveToPoint(p)
} else {
path.addLineToPoint(p)
}
mask.path = path.CGPath
}
}
}
objective-C :
#import "PanView.h"
@implementation PanView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self _init];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self _init];
}
return self;
}
- (void)_init {
self.layer.backgroundColor = [UIColor greenColor].CGColor;
CALayer *green = [CALayer layer];
green.frame = self.layer.bounds;
green.backgroundColor = [UIColor redColor].CGColor;
[self.layer addSublayer:green];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.frame = green.bounds;
mask.strokeColor = [UIColor whiteColor].CGColor;
mask.fillColor = [UIColor clearColor].CGColor;
mask.lineWidth = 10;
mask.lineJoin = kCALineJoinRound;
UIBezierPath *path = [UIBezierPath bezierPath];
mask.path = path.CGPath;
green.mask = mask;
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];
}
- (void)pan:(UIPanGestureRecognizer *)pan {
CGPoint p = [pan locationInView:self];
CALayer *green = (id)self.layer.sublayers.firstObject;
CAShapeLayer *mask = (id)green.mask;
UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:mask.path];
if (pan.state == UIGestureRecognizerStateBegan) {
[path moveToPoint:p];
} else {
[path addLineToPoint:p];
}
mask.path = path.CGPath;
}
@end
关于ios - 如何在 UIView 中剪切路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562976/