Как CAShapelayer
превращается из круга в квадрат (или наоборот) с CABasicAnimation
?Как CAShapelayer преобразуется из круга в квадрат (или наоборот) с анимацией?
ответ
После выполнения некоторых работ вокруг, я закончились с этим
Первый глобальный объект UIBezierPath
для квадратной и круглой дорожки, а также для объекта CAShapeLayer
.
@implementation Demo{
CAShapeLayer *shapeLayer;
UIBezierPath *sqPath;
UIBezierPath *crclePath;
}
Теперь настроить shapeLayer
и добавить слой, как показано ниже в viewDidLoad
.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
shapeLayer = [CAShapeLayer layer];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.lineWidth = 2;
shapeLayer.lineJoin = kCALineCapRound;
sqPath = [self makeSquare:self.view.center squareWidth:200];
shapeLayer.path = [sqPath CGPath];
crclePath = [self makeCircle:self.view.center radius:100];
[self.view.layer addSublayer:shapeLayer];
}
Ниже метод, который сделает идеальный квадрат
-(UIBezierPath*)makeSquare:(CGPoint)centrePoint squareWidth:(float)gain{
float x=centrePoint.x-(gain/2);
float y=centrePoint.y-(gain/2);
UIBezierPath *apath = [UIBezierPath bezierPath];
[apath moveToPoint:CGPointMake(x,y)];
[apath addLineToPoint:apath.currentPoint];
[apath addLineToPoint:CGPointMake(x+gain,y)];
[apath addLineToPoint:apath.currentPoint];
[apath addLineToPoint:CGPointMake(x+gain,y+gain)];
[apath addLineToPoint:apath.currentPoint];
[apath addLineToPoint:CGPointMake(x,y+gain)];
[apath addLineToPoint:apath.currentPoint];
[apath closePath];
return apath;
}
Ниже метод позволяет сделать окружность
- (UIBezierPath *)makeCircle:(CGPoint)center radius:(CGFloat)radius
{
UIBezierPath *circlePath = [UIBezierPath bezierPath];
[circlePath addArcWithCenter:center radius:radius startAngle:-M_PI endAngle:-M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:-M_PI/2 endAngle:0 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:0 endAngle:M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI/2 endAngle:M_PI clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI endAngle:-M_PI clockwise:YES];
[circlePath closePath];
return circlePath;
}
Наконец, анимация сделана в действии btnDone
, которые используют CABasicAnimation
для анимации преобразования от квадрата до круга или наоборот.
- (IBAction)btnDone:(id)sender {
btnDowrk.selected=!btnDowrk.selected;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 1;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
if (btnDowrk.selected) {
animation.fromValue = (__bridge id)(sqPath.CGPath);
animation.toValue = (__bridge id)(crclePath.CGPath);
shapeLayer.path = crclePath.CGPath;
}
else{
animation.fromValue = (__bridge id)(crclePath.CGPath);
animation.toValue = (__bridge id)(sqPath.CGPath);
shapeLayer.path = sqPath.CGPath;
}
[shapeLayer addAnimation:animation forKey:@"animatePath"];
}
Сообщите мне, что это работает для вас или нет? –
это преобразует квадрат в круг и Vice verca, но не точно показывает в вашем ответе –
, но я хочу, чтобы вы показали в exmaple –
Вы можете играть с cornerRadius
. Например,
UIView *testView = [[UIView alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];
CAShapeLayer *layer = [[CAShapeLayer alloc]initWithLayer:testView.layer]; // this is square layer
layer.cornerRadius = 25.0; // this is round layer
layer.cornerRadius = 0.0; // this is again square layer
Вы можете переключать виды непосредственно из круглых в квадратные и квадратные, чтобы округлить, как и выше!
, пожалуйста, прочтите мой вопрос –
Я хочу квадрат для круга в CABasicAnimation Мне не нужен UIView –
означает, что вы хотите изменить форму вида от квадрата до круга с анимацией? – Lion
Вот создать путь круг:
- (UIBezierPath *)circlePathWithCenter:(CGPoint)center radius:(CGFloat)radius
{
UIBezierPath *circlePath = [UIBezierPath bezierPath];
[circlePath addArcWithCenter:center radius:radius startAngle:0 endAngle:M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI/2 endAngle:M_PI clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI endAngle:3*M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:3*M_PI/2 endAngle:M_PI clockwise:YES];
[circlePath closePath];
return circlePath;
}
Вот квадратный путь:
- (UIBezierPath *)squarePathWithCenter:(CGPoint)center size:(CGFloat)size
{
CGFloat startX = center.x-size/2;
CGFloat startY = center.y-size/2;
UIBezierPath *squarePath = [UIBezierPath bezierPath];
[squarePath moveToPoint:CGPointMake(startX, startY)];
[squarePath addLineToPoint:CGPointMake(startX+size, startY)];
[squarePath addLineToPoint:CGPointMake(startX+size, startY+size)];
[squarePath addLineToPoint:CGPointMake(startX, startY+size)];
[squarePath closePath];
return squarePath;
}
анимация Часть
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 1;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.fromValue = (__bridge id)(self.stateLayer.path);
animation.toValue = (__bridge id)(self.stopPath.CGPath);
self.stateLayer.path = self.stopPath.CGPath;
[self.stateLayer addAnimation:animation forKey:@"animatePath"];
- 1. Проблема с CAShapeLayer и анимацией
- 2. Анимация CAShapeLayer с волновой анимацией
- 3. Проблема с анимацией CAShapeLayer iOS7
- 4. Текст круга с анимацией jquery
- 5. Как вращать дугу CAShapeLayer вокруг круга?
- 6. Изображение круга показывается как квадрат в OpenGL
- 7. Центр круга CAShapeLayer в середине экрана
- 8. Анимировать путь беззерцания CAShapeLayer с анимацией из центра
- 9. Рисовать границу вокруг круга с анимацией
- 10. Анимация CAShapeLayer для рисования круга прогресса
- 11. View.setX преобразует фон моего круга в квадрат
- 12. CAShapeLayer: Нахождение пересекаемых площади 3 круга
- 13. Как целое число преобразуется в строку и наоборот?
- 14. Как изменить форму прямоугольника в форме круга с анимацией
- 15. Проблемы с CAGradientLayer для анимированного круга, созданного с использованием CAShapeLayer
- 16. Как добавить ярлык или текст, чтобы CAShapeLayer
- 17. Как создать круг, квадрат или треугольник с JavaScript в HTML?
- 18. Как найти центр круга, используя наименьший квадрат, подходящий в python?
- 19. Как повернуть объект CAShapeLayer?
- 20. CAShapeLayer с подслоем CAShapeLayer slow
- 21. html canvas - рисунок круга с анимацией и числом
- 22. Как удалить CAShapeLayer из UIScrollView?
- 23. d3.js - как правильно расположить квадрат `squre` вокруг« круга »
- 24. Трансформация CAShapeLayer
- 25. Почему я получаю квадрат вместо круга в pygame?
- 26. CAShapeLayer с CIFilters
- 27. Как заполнить CAShapeLayer угловым градиентом?
- 28. Вызов Jython из Python (или наоборот)
- 29. CAShapeLayer замедление вращения интерфейса
- 30. Неверный setStrokeEnd CAShapeLayer
Какая часть сложна? Техника анимации в целом или особенности маскировки фигуры? – Avi
Я хочу преобразование из круга в квадрат сэр –
Радиус угла отрегулирован вниз до нуля. – Avi