UIImageView 上的旋转动画

发布于 2024-10-05 13:16:05 字数 2622 浏览 6 评论 0原文

我有一张阳光图像。我喜欢把它放在背景上,让它以慢动作连续旋转。

图像是这样的。

alt text

我尝试用 CABasicAnimation 旋转它,但它旋转整个框架..我只想让阳光在背景旋转而不是整个框架..

有什么办法可以做到吗???

更新:

这是我正在做的事情...请指出我的错误...:(

我没有明白你已经解释过的内容..:(

这是我正在做的事情...

 - (void)viewDidLoad {
sunraysContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
sunraysContainer.clipsToBounds = YES;
[self.view addSubview:sunraysContainer];


sunrays = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[sunrays setImage:[UIImage imageNamed:@"sunlight-background copy2.jpg"]];
[sunraysContainer addSubview:sunrays];

backgroundBuilding = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[backgroundBuilding setImage:[UIImage imageNamed:@"hira-background_fade.png"]];
 [sunraysContainer addSubview:backgroundBuilding];

[UIView beginAnimations:nil context:nil];
 [UIView setAnimationDuration:5];
 CABasicAnimation *rotationAnimation;
 rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
 rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
 rotationAnimation.duration = 1;
 rotationAnimation.cumulative = YES;
 rotationAnimation.repeatCount = 10;
 rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
 [sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
 [UIView commitAnimations];

 }

更新...

我做了你说的玉米片...谢谢你的回复,但我得到一个空白屏幕..:(

我已经编码了...

   sunrays = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sunlight-background copy2.jpg"]];
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0,0,sunrays.frame.size.height,sunrays.frame.size.height)];
[container setClipsToBounds:YES];
[container addSubview:sunrays];
[sunrays setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)]; 
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:5];
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
rotationAnimation.duration = 1;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 10;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
[UIView commitAnimations];

代码有什么问题?

I have a sunrays image. I like to put it on the background and make it rotate continuosly in a slow motion..

The image is this..

alt text

i've tried rotating it with CABasicAnimation, but it rotates the whole frame.. i want just the sunrays to revolve at the background not the whole frame..

Is there any way to do it???

Update:

Here is what m doing...please point out my mistakes... :(

i didn't got wat u've explained.. :(

here is what m doing...

 - (void)viewDidLoad {
sunraysContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
sunraysContainer.clipsToBounds = YES;
[self.view addSubview:sunraysContainer];


sunrays = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[sunrays setImage:[UIImage imageNamed:@"sunlight-background copy2.jpg"]];
[sunraysContainer addSubview:sunrays];

backgroundBuilding = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[backgroundBuilding setImage:[UIImage imageNamed:@"hira-background_fade.png"]];
 [sunraysContainer addSubview:backgroundBuilding];

[UIView beginAnimations:nil context:nil];
 [UIView setAnimationDuration:5];
 CABasicAnimation *rotationAnimation;
 rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
 rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
 rotationAnimation.duration = 1;
 rotationAnimation.cumulative = YES;
 rotationAnimation.repeatCount = 10;
 rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
 [sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
 [UIView commitAnimations];

 }

Update...

I did what u said nacho...thanks for your reply,but m getting a blankscreen.. :(

i've coded dis...

   sunrays = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sunlight-background copy2.jpg"]];
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0,0,sunrays.frame.size.height,sunrays.frame.size.height)];
[container setClipsToBounds:YES];
[container addSubview:sunrays];
[sunrays setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)]; 
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:5];
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
rotationAnimation.duration = 1;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 10;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
[UIView commitAnimations];

what is wrong wid the code??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

肩上的翅膀 2024-10-12 13:16:05

好吧,我认为你应该生成不同的图像,然后尝试对其进行动画处理。

imgLoading.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed:@"Img1.png"]
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:30.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:60.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:90.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:120.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:150.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:180.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:210.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:240.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:270.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:300.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:330.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:360.0]], nil];

imgLoading.animationRepeatCount=0;
imgLoading.animationDuration=.5;
[imgLoading startAnimating];

在上面的代码中,我单独添加了图像,但你可以在循环中填充它们。

- (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle

{

CGFloat angleInRadians = angle * (M_PI / 180);
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGRect imgRect = CGRectMake(0, 0, width, height);
CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef bmContext = CGBitmapContextCreate(NULL,
                                               rotatedRect.size.width,
                                               rotatedRect.size.height,
                                               8,
                                               0,
                                               colorSpace,
                                               kCGImageAlphaPremultipliedFirst);
CGContextSetAllowsAntialiasing(bmContext, YES);
CGContextSetShouldAntialias(bmContext, YES);
CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
CGColorSpaceRelease(colorSpace);
CGContextTranslateCTM(bmContext,
                      +(rotatedRect.size.width/2),
                      +(rotatedRect.size.height/2));
CGContextRotateCTM(bmContext, angleInRadians);
CGContextTranslateCTM(bmContext,
                      -(rotatedRect.size.width/2),
                      -(rotatedRect.size.height/2));
CGContextDrawImage(bmContext, CGRectMake(0, 0,
                                         rotatedRect.size.width,
                                         rotatedRect.size.height),
                   imgRef);



CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
CFRelease(bmContext);
[(id)rotatedImage autorelease];

return rotatedImage;

}

上述函数可用于给出旋转图像。

Well I think you should generate different images and then try to animate this

imgLoading.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed:@"Img1.png"]
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:30.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:60.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:90.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:120.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:150.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:180.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:210.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:240.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:270.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:300.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:330.0]],
                              [UIImage imageWithCGImage:
                               [self CGImageRotatedByAngle:
                                [[UIImage imageNamed:@"Img1.png"] CGImage]angle:360.0]], nil];

imgLoading.animationRepeatCount=0;
imgLoading.animationDuration=.5;
[imgLoading startAnimating];

In the above code I have added the images separately but you can populate them in a loop.

- (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle

{

CGFloat angleInRadians = angle * (M_PI / 180);
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGRect imgRect = CGRectMake(0, 0, width, height);
CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef bmContext = CGBitmapContextCreate(NULL,
                                               rotatedRect.size.width,
                                               rotatedRect.size.height,
                                               8,
                                               0,
                                               colorSpace,
                                               kCGImageAlphaPremultipliedFirst);
CGContextSetAllowsAntialiasing(bmContext, YES);
CGContextSetShouldAntialias(bmContext, YES);
CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
CGColorSpaceRelease(colorSpace);
CGContextTranslateCTM(bmContext,
                      +(rotatedRect.size.width/2),
                      +(rotatedRect.size.height/2));
CGContextRotateCTM(bmContext, angleInRadians);
CGContextTranslateCTM(bmContext,
                      -(rotatedRect.size.width/2),
                      -(rotatedRect.size.height/2));
CGContextDrawImage(bmContext, CGRectMake(0, 0,
                                         rotatedRect.size.width,
                                         rotatedRect.size.height),
                   imgRef);



CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
CFRelease(bmContext);
[(id)rotatedImage autorelease];

return rotatedImage;

}

The Above function can be used to give the rotated images..

2024-10-12 13:16:05

我认为你的方法是正确的;)你必须有一个夹住它的容器,这样它看起来就不会像孔框架在旋转。

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
UIView *container = [UIView alloc] initWithFrame:CGRectMake(0,0,imageView.frame.size.height, image.frame.size.height)]; //i used the height because is the min(height, width).
[container setClipsToBounds:YES];
[container addSubview:imageView];
[imageView setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)];
//animate your image here
...

还。如果可能的话,使用 CALayer 而不是 imageView ;)

CALayer *imageLayer = [CALayer layer];
imageLayer.contents = (id)[UIImage imageNamed:@"myimage.png"].CGImage;
// and do basically the same as above,
[container.layer addSublayer:imageLayer];
//...

注意:上面的代码是大脑编译的,所以可能会有一些小错误,但想法很明确;)

希望它有帮助

编辑:

嘿;)我认为你忘记添加容器你的观点。 ;)

我刚刚尝试了代码,我意识到容器的帧计算不精确。(即使你不这样做它也会工作,但动画看起来有点难看)
这是代码:

    UIImage *image = [UIImage imageNamed:@"sunrays.jpg"];
    UIImageView *sunrays = [[UIImageView alloc] initWithImage:image];
    float side = (MIN(image.size.height, image.size.width)/(2.0*sqrt(2)));
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0,0,side,side)];
    [container setClipsToBounds:YES];
    [container addSubview:sunrays];
    [sunrays setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)]; 

    [self.view addSubview:container]; //you forgot this? ;)

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:5];
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 10;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    [sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    [UIView commitAnimations];

I think you are in the correct way ;) You have to have a container that clips it so it won't look like the hole frame is rotating.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
UIView *container = [UIView alloc] initWithFrame:CGRectMake(0,0,imageView.frame.size.height, image.frame.size.height)]; //i used the height because is the min(height, width).
[container setClipsToBounds:YES];
[container addSubview:imageView];
[imageView setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)];
//animate your image here
...

Also. if possible use a CALayer instead of an imageView ;)

CALayer *imageLayer = [CALayer layer];
imageLayer.contents = (id)[UIImage imageNamed:@"myimage.png"].CGImage;
// and do basically the same as above,
[container.layer addSublayer:imageLayer];
//...

NOTE: above code is brain compiled, so there might be some small errors, but the idea is clear ;)

Hope it helps

EDIT:

Hey ;) I think you forgot to add container to your view. ;)

And I just tried the code and I realized that container's frame calculation was inexact.(Even if you don't to this it will work, but the animation will look a little bit ugly)
Here is the code:

    UIImage *image = [UIImage imageNamed:@"sunrays.jpg"];
    UIImageView *sunrays = [[UIImageView alloc] initWithImage:image];
    float side = (MIN(image.size.height, image.size.width)/(2.0*sqrt(2)));
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0,0,side,side)];
    [container setClipsToBounds:YES];
    [container addSubview:sunrays];
    [sunrays setCenter:CGPointMake(container.bounds.size.width/2, container.bounds.size.height/2)]; 

    [self.view addSubview:container]; //you forgot this? ;)

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:5];
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0 * 4.0];
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 10;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    [sunrays.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    [UIView commitAnimations];
枉心 2024-10-12 13:16:05

我知道这是很旧的帖子。
一种解决方案是使图像的黄色部分透明。您可以使用免费工具 pngweasel。使黄色部分透明 - 这将只给出太阳光线的图像。此图像使用纯黄色背景。现在您可以使用以下代码轻松旋转新的(太阳光线)图像

CABasicAnimation *rotate;
rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotate.fromValue = [NSNumber numberWithFloat:0];
rotate.toValue = [NSNumber numberWithFloat:(0.0175*180)]; //[NSNumber numberWithFloat:deg2rad(10)];
rotate.duration = 0.5;
rotate.repeatCount = 1;
[self.image.layer addAnimation:rotate forKey:@"10"];

I know it is very old post.
One solution is to make your image transparent in yellow part. You can use free tool pngweasel. Make yellow part transparent - This will give only image of sun rays. Use plain yellow background for this image. Now you can easily rotate new (sun rays) image using below code

CABasicAnimation *rotate;
rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotate.fromValue = [NSNumber numberWithFloat:0];
rotate.toValue = [NSNumber numberWithFloat:(0.0175*180)]; //[NSNumber numberWithFloat:deg2rad(10)];
rotate.duration = 0.5;
rotate.repeatCount = 1;
[self.image.layer addAnimation:rotate forKey:@"10"];
橙幽之幻 2024-10-12 13:16:05

Swift 3:

var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
imageView.layer.add(rotationAnimation, forKey: "rotationAnimation")

这是 UIView 的扩展函数,用于处理启动和启动。停止旋转操作:

extension UIImageView {

    func startRotation() {
        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = NSNumber(value: Double.pi)
        rotation.duration = 5.0
        rotation.isCumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.add(rotation, forKey: "rotationAnimation")
    }

    func stopRotation() {
        self.layer.removeAnimation(forKey: "rotationAnimation")
    }
}

现在使用 UIView.animation 闭包:

UIView.animate(withDuration: 0.5, animations: { 
      imageView.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) 
}) { (isAnimationComplete) in
    // Animation completed 
}

使用扩展查看结果:

在此处输入图像描述

Swift 3:

var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
imageView.layer.add(rotationAnimation, forKey: "rotationAnimation")

Here is an extension functions for UIView that handles start & stop rotation operations:

extension UIImageView {

    func startRotation() {
        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = NSNumber(value: Double.pi)
        rotation.duration = 5.0
        rotation.isCumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.add(rotation, forKey: "rotationAnimation")
    }

    func stopRotation() {
        self.layer.removeAnimation(forKey: "rotationAnimation")
    }
}

Now using, UIView.animation closure:

UIView.animate(withDuration: 0.5, animations: { 
      imageView.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) 
}) { (isAnimationComplete) in
    // Animation completed 
}

See the result using extension:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文