Как сделать мой UIBezierPath анимированным с CAShapeLayer?
Я пытаюсь оживить UIBezierPath, и я установил CAShapeLayer, чтобы попытаться это сделать. К сожалению, анимация не работает, и я не уверен, что какой-либо из слоев оказывает какое-либо влияние (поскольку код делает то же самое, что и раньше, когда у меня были слои).
Вот реальный код - любил бы любую помощь. Draw2D - это реализация UIView, встроенная в UIViewController. Весь чертеж происходит внутри класса Draw2D. Вызов [_helper createDrawing...] просто заполняет переменную _uipath точками.
Draw2D.h определяет следующие свойства:
#define defaultPointCount ((int) 25)
@property Draw2DHelper *helper;
@property drawingTypes drawingType;
@property int graphPoints;
@property UIBezierPath *uipath;
@property CALayer *animationLayer;
@property CAShapeLayer *pathLayer;
- (void)refreshRect:(CGRect)rect;
ниже - фактическая реализация:
//
// Draw2D.m
// Draw2D
//
// Created by Marina on 2/19/13.
// Copyright (c) 2013 Marina. All rights reserved.
//
#import "Draw2D.h"
#import"Draw2DHelper.h"
#include <stdlib.h>
#import "Foundation/Foundation.h"
#import <QuartzCore/QuartzCore.h>
int MAX_WIDTH;
int MAX_HEIGHT;
@implementation Draw2D
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
if (self.pathLayer != nil) {
[self.pathLayer removeFromSuperlayer];
self.pathLayer = nil;
}
self.animationLayer = [CALayer layer];
self.animationLayer.frame = self.bounds;
[self.layer addSublayer:self.animationLayer];
CAShapeLayer *l_pathLayer = [CAShapeLayer layer];
l_pathLayer.frame = self.frame;
l_pathLayer.bounds = self.bounds;
l_pathLayer.geometryFlipped = YES;
l_pathLayer.path = _uipath.CGPath;
l_pathLayer.strokeColor = [[UIColor grayColor] CGColor];
l_pathLayer.fillColor = nil;
l_pathLayer.lineWidth = 1.5f;
l_pathLayer.lineJoin = kCALineJoinBevel;
[self.animationLayer addSublayer:l_pathLayer];
self.pathLayer = l_pathLayer;
[self.layer addSublayer:l_pathLayer];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect :(int) points :(drawingTypes) type //:(Boolean) initial
{
//CGRect bounds = [[UIScreen mainScreen] bounds];
CGRect appframe= [[UIScreen mainScreen] applicationFrame];
CGContextRef context = UIGraphicsGetCurrentContext();
_helper = [[Draw2DHelper alloc ] initWithBounds :appframe.size.width :appframe.size.height :type];
CGPoint startPoint = [_helper generatePoint] ;
[_uipath moveToPoint:startPoint];
[_uipath setLineWidth: 1.5];
CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
CGPoint center = CGPointMake(self.center.y, self.center.x) ;
[_helper createDrawing :type :_uipath :( (points>0) ? points : defaultPointCount) :center];
self.pathLayer.path = (__bridge CGPathRef)(_uipath);
[_uipath stroke];
[self startAnimation];
}
- (void) startAnimation {
[self.pathLayer removeAllAnimations];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 3.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[self.pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
- (void)drawRect:(CGRect)rect {
if (_uipath == NULL)
_uipath = [[UIBezierPath alloc] init];
else
[_uipath removeAllPoints];
[self drawRect:rect :self.graphPoints :self.drawingType ];
}
- (void)refreshRect:(CGRect)rect {
[self setNeedsDisplay];
}
@end
Я знаю, что, вероятно, есть очевидная причина того, почему путь не анимируется, поскольку он рисует (в отличие от того, чтобы сразу показать, что происходит сейчас), но я так долго смотрел на это, что я просто не вижу этого.
Кроме того, если кто-нибудь может порекомендовать базовый праймер на CAShapeLayers и анимацию вообще, я был бы признателен. Не подходите ни к чему хорошему.
заблаговременно.
Ответы
Ответ 1
Похоже, вы пытаетесь анимировать внутри drawRect
(косвенно, по крайней мере). Это не совсем понятно. Вы не живете в пределах drawRect
. drawRect
используется для рисования одного кадра. Некоторая анимация выполняется с помощью таймеров или CADisplayLink
, которая повторно вызывает setNeedsDisplay
(что приведет к тому, что iOS вызовет ваш drawRect
), в течение которого вы можете нарисовать один кадр, который показывает ход анимации в этой точке. Но у вас просто нет drawRect
, инициирующего любую анимацию самостоятельно.
Но, поскольку вы используете Core Animation CAShapeLayer
и CABasicAnimation
, вам вообще не нужен пользовательский drawRect
. Quartz Core Animation просто заботится обо всем для вас. Например, вот мой код для анимации рисунка UIBezierPath
:
#import <QuartzCore/QuartzCore.h>
@interface View ()
@property (nonatomic, weak) CAShapeLayer *pathLayer;
@end
@implementation View
/*
// I'm not doing anything here, so I can comment this out
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
*/
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
// It doesn't matter what my path is. I could make it anything I wanted.
- (UIBezierPath *)samplePath
{
UIBezierPath *path = [UIBezierPath bezierPath];
// build the path here
return path;
}
- (void)startAnimation
{
if (self.pathLayer == nil)
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [[self samplePath] CGPath];
shapeLayer.strokeColor = [[UIColor grayColor] CGColor];
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 1.5f;
shapeLayer.lineJoin = kCALineJoinBevel;
[self.layer addSublayer:shapeLayer];
self.pathLayer = shapeLayer;
}
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 3.0;
pathAnimation.fromValue = @(0.0f);
pathAnimation.toValue = @(1.0f);
[self.pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
@end
Затем, когда я хочу начать рисовать анимацию, я просто вызываю метод startAnimation
. Мне, вероятно, даже не нужен подкласс UIView
вообще для чего-то столь же простого, как это, поскольку я фактически не изменяю поведение UIView
. Определенно, вы подклассом UIView
с пользовательской реализацией drawRect
, но здесь это не нужно.
Вы запросили несколько ссылок: