UIImageView animation is not working [duplicate] - ios

This question already has answers here:
Swift - How to animate Images?
(7 answers)
Closed 6 years ago.
I am working on the UIImageView transition in swift. I an storing six images in an array and giving that array to “imageview.animationImages
” and I am trying to making it to work as ‘Gif animation’ the code I wrote is as follows :
logoImages = NSMutableArray(array: ["backGround4.jpeg","backGround3.jpeg","backGround.jpeg","16.jpeg","23.jpeg","backGround1.jpeg"])
imageview.animationImages = NSArray(array: ["backGround4.jpeg","backGround3.jpeg","backGround.jpeg","16.jpeg","23.jpeg","backGround1.jpeg"]) as? [UIImage]
imageview.animationDuration = 1.5
imageview.animationRepeatCount = 1
imageview.startAnimating()
It is not working.Can anyone please tell me what is the mistake I am doing here?
Thanks In Advance

First correct your image name like backGround1.jpeg, backGround2.jpeg etc..
After that create one image array which will hold all your images:
var imageArray = [UIImage]()
Then add all images in image array:
for var i = 1; i < totalImageCount; i++ {
let image = UIImage(named: "backGround4\(i).png")
imageArray.append(image!)
}
After that you can create animation this way:
imageview.animationImages = imageArray
imageview.animationDuration = 1.5
imageview.startAnimating()

Please convert string to UIImage like this:
imageview.animationImages = NSArray(array: ["backGround4.jpeg","backGround3.jpeg","backGround.jpeg","16.jpeg","23.jpeg","backGround1.jpeg"].map({ (string) -> UIImage in
UIImage(named: string)! })) as? [UIImage]

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

Related

Swift 5 or up - Image view on pickerview

My images from "2.jpg" to "7.jpg" shows but the first image("1.jpg") on my simulator. what do I need to change?
var imageFileName = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg"]
for i in 0 ..< MAX_ARRAY_NUM {
let image = UIImage(named: imageFileName[i])
imageArray.append(image)
lblImageFileName.text = imageFileName[0]
imageView.image = imageArray[0]
enter image description here
enter image description here
I think you should change below two lines
lblImageFileName.text = imageFileName[0]
imageView.image = imageArray[0]
to,
lblImageFileName.text = imageFileName[i]
imageView.image = imageArray[i]
as you used variable i to represent index

How to display an image if variable equals a special number using swift 3?

I have three pictures (lvl1.png, lvl2.png, lvl3.png) and an variable (let level = 1). What should I do to display an image named 'lvl2' if level = 2, and when level = 3 I need to show the last image (lvl3.png)?
you can use:
let image = UIImage(named: "lvl\(level).png")
or
let image: UIImage!
switch level {
case 1:
image = UIImage(named: "lvl1.png")
case 2:
image = UIImage(named: "lvl2.png")
case 3:
image = UIImage(named: "lvl3.png")
default:
image = UIImage()
}
avatar.image = image
you can try
imgName = "lvl" + String(lavel)
imageView.image = UIImage(named: imgName)
Another alternative is to create a method that returns an image, like so:
func imageFor(level: Int) -> UIImage? {
let image = UIImage(named: "lvl\(currentLevel)")
return image
}
Usage:
var currentLevel = 1
let image = imageFor(level: currentLevel)
You can try
var level = 1 {
didSet {
self.imageview.image = UIImage(named: "lvl\(level)")
}
}
when you change the level the imageView will change automatically

Animate icons change

I am working on my first application, its a mathematical riddles app. The player can get a hint that will reveal one of the variables - it's basically replacing one image with another. Sometimes I am replacing more than one image so I am using a loop that replace all of them. I want the old image to fade and be replaced with the new image, the answer. Also I would like them to fade one after the other, meaning that there will be a small delay between one image replacement animation to the next.
func changeHintIcons () {
var labelsArr = [[firstEquationFirstElemnt,firstEquationSecondElemnt,firstEquationThirdElemnt],[secondEquationFirstElemnt,secondEquationSecondElemnt,secondEquationThirdElemnt],[thirdEquationFirstElemnt,thirdEquationSecondElemnt,thirdEquationthirdElemnt],[fourthEquationFirstElemnt,fourthEquationSecondElemnt,fourthEquationThirdElemnt], [fifthEquationFirstElemnt,fifthEquationSecondElemnt,fifthEquationThirdElemnt]]
let col:Int = Int(arc4random_uniform(UInt32(gameDifficulty.stages[gameLevel].umberOfVariables)))
let row:Int = Int(arc4random_uniform(UInt32(2))) * 2
let var_to_show = current_equations[col][row]
let image_name = "answer.num.\(var_to_show)"
for i in 0..<current_equations.count {
for j in 0..<current_equations[i].count {
if (current_equations[i][j] == var_to_show) {
var image_index = j
if (j > 0) {
image_index = Int(j/2) //Converting index
}
labelsArr[i][image_index]!.image = UIImage(named: image_name)! //Replacing the image
}
}
}
}
One last thing, what if I want to use in an animation instead of letting the image simply fade out? What are my options and how can I implement them?
Ok I found the answer. Basically swift allows you to create your animation by projecting a set of images one after the other. Follow these steps:
1. Copy animation images to assets folder
2. create an array of UIImages
3. Do the same things as I did in the animate function
Main code -
var animationArray = createImageArray(total: 14, imagePrefix: "hint.animation")
animationArray.append(UIImage(named: imageHintAnswer)!)
animate(imageView: labelsArr[i][image_index]!, images: animationArray)
Functions -
func createImageArray(total: Int, imagePrefix: String) -> [UIImage] {
var imageArray:[UIImage] = []
for imageCount in 1..<total {
let imageName = "\(imagePrefix).\(imageCount)"
let image = UIImage(named: imageName)!
imageArray.append(image)
}
return imageArray
}
func animate(imageView: UIImageView, images: [UIImage]) {
imageView.animationImages = images
imageView.animationDuration = 0.7
imageView.animationRepeatCount = 1
imageView.startAnimating()
}

Reduce Parse PFFile, images and text

I have a UItextView which I place images and type text into, and once I have finished with the TextView I then upload the contents of that textView to Parse.
If I only add 1 image to the textView it lets me upload the UITextView contents to Parse without any problems, but when I add more than 1 Image I get the error "data is larger than 10mb etc...".
Now I am wondering how I can reduce the size of this PFFile?
Or is their a way to reduce the size of the images before or after adding the to the textView? possibly extract the from th etextView and reduce there size before uploading to Parse?
This is my code:
Here is where the text & images from the textView are stored:
var recievedText = NSAttributedString()
And here Is how I upload it to Parse:
let post = PFObject(className: "Posts")
let uuid = NSUUID().UUIDString
post["username"] = PFUser.currentUser()!.username!
post["titlePost"] = recievedTitle
let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(recievedText)
post["textPost"] = PFFile(name:"text.txt", data:data)
post["uuid"] = "\(PFUser.currentUser()!.username!) \(uuid)"
if PFUser.currentUser()?.valueForKey("profilePicture") != nil {
post["profilePicture"] = PFUser.currentUser()!.valueForKey("profilePicture") as! PFFile
}
post.saveInBackgroundWithBlock ({(success:Bool, error:NSError?) -> Void in
})
Best regards.
How I add the images
image1.image = images[1].imageWithBorder(40)
let oldWidth1 = image1.image!.size.width;
let scaleFactor1 = oldWidth1 / (blogText.frame.size.width - 10 )
image1.image = UIImage(CGImage: image1.image!.CGImage!, scale: scaleFactor1, orientation: .Up)
let attString1 = NSAttributedString(attachment: image1)
blogText.textStorage.insertAttributedString(attString1, atIndex: blogText.selectedRange.location)
You should to resize the picture to make sure it is small size for upload. See this answer

Store series of captured images into array

In the function below(didPressTakePhoto), I am trying to take a series of pictures(10 in this case), store them into an array and display them as an animation in the "gif". Yet the program keeps crashing and I have no idea why. This is all after one button click, hence the function name. Also, I tried taking the animation code outside the for loop, but the imageArray would then lose it's value for some reason.
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
//var counter = 0
if sampleBuffer != nil {
for var index = 0; index < 10; ++index {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProviderCreateWithCFData(imageData)
let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)
var imageArray: [UIImage] = []
let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
imageArray.append(image)
imageArray.insert(image, atIndex: index++)
self.tempImageView.image = image
self.tempImageView.hidden = false
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
var gif: UIImageView!
gif.animationImages = imageArray
gif.animationRepeatCount = -1
gif.animationDuration = 1
gif.startAnimating()
}
}
})
}
}
Never try to make an array of images (i.e., a [UIImage] as you are doing). A UIImage is very big, so an array of many images is huge and you will run out of memory and crash.
Save your images to disk, maintaining only references to them (i.e. an array of their names).
Before using your images in the interface, reduce them to the actual physical size you will need for that interface. Using a full-size image for a mere screen-sized display (or smaller) is a huge waste of energy. You can use the ImageIO framework to get a "thumbnail" smaller version of the image from disk without wasting memory.
You are creating a new [UIImage] in every iteration of the loop, so in the last iteration there's only one image, you should take the imageArray creation out of the loop. Having said that, you should take into account what #matt answered

Resources