我想创建一个“创建视图副本,将此副本从一个点移动到另一个点,同时降低不透明度直到它完全消失”的动画。
我想我需要通过CABasicAnimation
这样做,所以我尝试了类似的东西:
CGPoint point = CGPointMake(200, 0);
// copy layer
CALayer *layer = [[CALayer alloc] initWithLayer:self.animatedView.layer];
[self.animatedView.layer addSublayer:layer];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue = [layer valueForKey:@"position"];
animation.toValue = [NSValue valueWithCGPoint:point];
animation.duration = 2.0f;
CABasicAnimation *oanimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
oanimation.fromValue = @1;
oanimation.toValue = @0;
oanimation.duration = 1.0f;
// move copy layer
[layer addAnimation:animation forKey:@"position"];
[layer addAnimation:oanimation forKey:@"opacity"];
但是nothings附加,我认为这是关于文档的正常情况:
此初始值设定项用于创建图层的阴影副本 例如,对于presentationLayer方法。在任何方面使用此方法 其他情况会产生不确定的行为。例如,不要 使用此方法初始化具有现有图层的新图层 内容。
之前有人做过这种动画吗?
感谢您的帮助。
答案 0 :(得分:1)
UIGraphicsBeginImageContext(theView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[theView.layer renderInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:screenShot];
imgView.frame = theView.frame;
[self.view addSubview:imgView];
然后玩'imgView':)
答案 1 :(得分:0)
我在Swift 4.2中采用了@Sriram解决方案,并且更喜欢使用适应性更强的CALayer代替UIImageView
。
// We use the screen's scale to support Retina displays
UIGraphicsBeginImageContextWithOptions(viewToCopy.frame.size, false, UIScreen.main.scale)
if let context: CGContext = UIGraphicsGetCurrentContext() {
// We convert the layer of the viewToCopy into an UIImage
viewToCopy.layer.render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// We create a layer that will hold the image. This layer can be animated further down the road.
let layer = CALayer()
layer.contents = screenshot?.cgImage // Don't forget .cgImage, otherwise it won't work
layer.frame = viewToCopy.frame // For example
view.layer.addSublayer(layer)
}
我想这对于大多数情况都可以正常工作,但是在使用UIVisualEffectView
进行此操作时遇到了一些问题(效果已失效)。所以我不得不找出第二种解决方案。
首先,您需要对UIView
进行一个小扩展,以便能够轻松复制它。我使用了this answer,但为了清楚起见,我将其复制在这里。
// MARK: - UIView + Copy
extension UIView {
func copyView<T: UIView>() -> T {
return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
}
}
拥有此视图后,您可以复制视图,添加视图并将其布局到视图层次结构中,并像使用其他UIView
一样使用它。
let animationCardView = cardView.copyView()
animationCardView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationCardView)
NSLayoutConstraint.activate([animationCardView.leadingAnchor.constraint(equalTo: cardView.leadingAnchor),
animationCardView.trailingAnchor.constraint(equalTo: cardView.trailingAnchor),
animationCardView.topAnchor.constraint(equalTo: cardView.topAnchor),
animationCardView.bottomAnchor.constraint(equalTo: cardView.bottomAnchor)])