简体   繁体   English

斯威夫特 - 如何动画图像?

[英]Swift - How to animate Images?

I'm trying to animate images in particular time- duration. 我试图在特定的持续时间内动画图像。 It is working fine in Objective C. However, it is not working for Swift, where is my mistake? 它在Objective C中运行正常。但是,它不适用于Swift,我的错误在哪里?

The code for Objective-C is - Objective-C的代码是 -

-(void)viewDidLoad
{
   [super viewDidLoad];
   NSMutableArray *imgListArray=[NSMutableArray array];
   for (int i=0; i<=11; i++)

   {
       NSString *strImageName=[NSString stringWithFormat:@"c%d.png", i];
       NSLog(@"%@",strImageName);
       UIImage *image=[UIImage imageNamed:strImageName];
       [imgListArray addObject:image];
   }

   self.imgView.animationImages = imgListArray;
   self.imgView.animationDuration =1.0f;    
   [self.imgView startAnimating];
   // Do any additional setup after loading the view, typically from a nib
}

The Code for swift is- 迅捷守则是 -

override func viewDidLoad()
{
   super.viewDidLoad()

   var imgListArray :NSMutableArray = []
   for countValue in 1...11
   {
      var strImageName : String = "c\(countValue).png"
      var image = UIImage(named:strImageName) // suggested by Anil
      imgListArray.addObject(image)
   }

   // Swift code HERE for Objective c
}
[UIImage imageNamed (strImageName)]

This not swift code. 这不是快速的代码。 In swift it would be 很快就会

UIImage(named:strImageName)  

Modified code: 修改后的代码

var imgListArray :NSMutableArray = []
for countValue in 1...11
    {

        var strImageName : String = "c\(countValue).png"
        var image  = UIImage(named:strImageName)
        imgListArray .addObject(image)
    }

    self.imageView.animationImages = imgListArray;
    self.imageView.animationDuration = 1.0
    self.imageView.startAnimating()

for Swift 2, use [UIImage] instead. 对于Swift 2,请改用[UIImage]

var images: [UIImage] = []
for i in 1...2 {
    images.append(UIImage(named: "c\(i)")!)
}
myImageView.animationImages = images
myImageView.animationDuration = 1.0
myImageView.startAnimating()

In swift you can go one step further and have a simple line to do this: 在swift中你可以更进一步,并有一个简单的行来做到这一点:

let loadingImages = (1...11).map { UIImage(named: "c\($0)")! }

Then you can do the rest and inject this into an imageView 然后你可以完成剩下的工作并将其注入imageView

self.imageView.animationImages = loadingImages
self.imageView.animationDuration = 1.0
self.imageView.startAnimating()

In swift 3 - Create Array of images and just animate that. 在swift 3中 - 创建图像阵列并只为其制作动画。

func animate_images()
{
    let myimgArr = ["1.jpg","2.jpg","3.jpg"]
    var images = [UIImage]()

    for i in 0..<myimgArr.count
    {
        images.append(UIImage(named: myimgArr[i])!)
    }

    imgView_ref.animationImages = images
    imgView_ref.animationDuration = 0.04
    imgView_ref.animationRepeatCount = 2
    imgView_ref.startAnimating()
}

And for stop animation just write 而对于停止动画只需写

 imgView_ref.stopAnimating()

another approach if you want to animate an array of images: 如果要为图像数组设置动画,请使用另一种方法:

var counter = 1
var timer = NSTimer()
@IBOutlet weak var someImg: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("doSomeAnimation"), userInfo: nil, repeats: true)
}

func doSomeAnimation() {
    //I have four pngs in my project, which are named frame1.png ... and so on


       if counter == 4 {

        counter = 1

        }else {

        counter++
    }

    someImg.image = UIImage(named: "frame\(counter).png")
}

Hope it helps!! 希望能帮助到你!!

For anyone running multiple animations, depending on a variable, try the below. 对于运行多个动画的任何人,根据变量,请尝试以下操作。

For example, you could run an animation sending 0 or 1 (maybe based on if your app knows its daytime or nighttime): 例如,您可以运行发送0或1的动画(可能基于您的应用是否知道其白天或夜晚):

func runAnimation (imgView: UIImageView, arrayPos: Int) {
    let timingArray = [7.0,10.0] //Durations of each
    let frameArray = [43,45]  //Frames for each
    var imgArray: Array<UIImage> = [] //Setup empty array 

    for i in 1 ... frameArray[arrayPos] {
        //Fill empty array with images!!
        let imageToAdd = UIImage(named: "animationNum_\(arrayPos)-frameNum_\(i)")
        imgArray.append(imageToAdd!)
    }
    imgView.animationImages = imgArray
    imgView.animationDuration = timingArray[arrayPos]
    imgView.animationRepeatCount = 2
    imgView.startAnimating()
}

Swift 3+ Swift 3+

UIImageViews can animate images in two different ways (the other answers already cover the first way in deep): UIImageViews可以用两种不同的方式为图像制作动画(其他答案已经涵盖了深层的第一种方式):

    • Create an [UIImage] array with the images to animate 创建一个[UIImage]数组,其中包含要设置动画的图像
    • Set the animationImages property of the view with this array 使用此数组设置视图的animationImages属性
    • Set the animationDuration property 设置animationDuration属性
    • Start the animation 开始动画

The following code uses #imageLiterals : 以下代码使用#imageLiterals

let images = [img1, img2, img3] // use of #imageLiterals here
let animation = UIImage.animatedImage(with: images, duration: 1)
self.myImageView.image = animation

Pro: 优点:

If you have to change the image of an UIImageView a lot and maybe one of those images should be animated, then you don't have to start/stop the animation every time anymore neither you need to set the animatedImages property back to nil to display the image stored in the image property of the image view. 如果你必须经常更改UIImageView的图像,并且可能其中一个图像应该是动画的,那么你不必每次都开始/停止动画,你也不需要将animatedImages属性设置回nil来显示存储在图像视图的图像属性中的图像。

Con: 缺点:

You can't start/stop the animation, if it's encapsulated in a single UIImage instead of an array. 如果动画封装在单个UIImage而不是数组中,则无法启动/停止动画。


More on #imageLiterals : 有关#imageLiterals更多#imageLiterals

If you want to use an image literal, either type imageLiteral or just type the name of an image from your assets folder and Xcode's code completion will suggest it. 如果要使用图像文字,请键入imageLiteral或只键入assets文件夹中的图像名称,Xcode的代码完成将建议它。

Further reading: 进一步阅读:

  • Another good blog post about using #imageLiterals and #colorLiterals with animations to follow. 另一个很好的博客文章有关使用#imageLiterals#colorLiterals与动画跟随。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM