How to generate random image using image view in swift - ios

I just followed treehouse course and create my first Fun Fact app.In that they generate a random array quotes.
Needed:
I have placed image view using storyboard.Already when pressing one button random array quotes will generate.But i need when that same button pressed a random image should generate.I am new to swift .!
This is factbook.swift
struct FactBook {
// stored in arry to show all quotes
let factsArray = [
"You have to dream before your dreams can come true.",
"To succeed in your mission, you must have single-minded devotion to your goal.",
"You have to dream before your dreams can come true.",
"Love your job but don’t love your company, because you may not know when your company stops loving you.",
"Failure will never overtake me if my definition to succeed is strong enough.",
]
//make a random quote
func randomFact() -> String {
//
// let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
//
let unsignedArrayCount = UInt32(factsArray.count)
let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
let randomNumber = Int(unsignedRandomNumber)
//
// let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
// let randomNumber = Int(signedRandomNumber)
return factsArray[randomNumber]
}
}
This is viewcontroller.swift
class ViewController: UIViewController {
#IBOutlet weak var funFactLabel: UILabel!
#IBOutlet weak var funFactButton: UIButton!
#IBOutlet weak var imgV: UIImageView!
let factBook = FactBook()
let colorWheel = ColorWheel()
//method to define
// let yourImage = UIImage(named: "apj")
// let imageview = UIImageView(image: yourImage)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
funFactLabel.text = factBook.randomFact()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "apj")!)
// let yourImage = UIImage(named: "apj")
// let imageview = UIImageView(image: yourImage)
// self.view.addSubview(imageview)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showFunFact() {
let randomColor = colorWheel.randomColor()
view.backgroundColor = randomColor
funFactButton.tintColor = randomColor
//funFactButton.tintColor = clearcolor
funFactLabel.text = factBook.randomFact()
}
}

The solution mainly is to use the same approach you have done with the random text. So to sum up, you should have an array of the images, and a function to select a random image. Then call that function from your view controller. A possible implementation to this approach is:
Add this array to your FactBook
let factsImagesArray = [
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png",
]
Add this method to your FactBook
func randomFactImage() -> UIImage {
let unsignedArrayCount = UInt32(factsImageArray.count)
let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
let randomNumber = Int(unsignedRandomNumber)
return UIImage(named: factsImageArray[randomNumber])!
}
and in your viewcontroller change showFunFact to:
#IBAction func showFunFact() {
let randomColor = colorWheel.randomColor()
view.backgroundColor = randomColor
funFactButton.tintColor = randomColor
funFactLabel.text = factBook.randomFact()
imgV.image = faceBook.randomFactImage()
}
Ofc you should have the image1.png, image2.png ... in your resources

#IBAction func randomimage(sender: AnyObject)
{
//list of Images in array
let image : NSArray = [ UIImage(named: "1.jpg")!,
UIImage(named: "2.jpg")!,
UIImage(named: "3.jpg")!,
UIImage(named: "4.jpg")!,
UIImage(named: "5.jpg")!,
UIImage(named: "6.jpg")!,
UIImage(named: "7.jpg")!]
//random image generating method
let imagerange: UInt32 = UInt32(image.count)
let randomimage = Int(arc4random_uniform(imagerange))
let generatedimage: AnyObject = image.objectAtIndex(randomimage)
self.myimage.image = generatedimage as? UIImage
}

Related

How to link an image to a sound randomly?

I have this code and it's working, but not as really want to. I'm new to Xcode/Swift/developing apps. I've made it watching tutorials and using some snippets as examples, but so far is working :)
I'd like to make it work in this way:
When I click on playSound and hear it, then I have to choose between leftImage and rightImage..the image that matches with the playSound. I've tried into many ways to get it work.. but nothing...I cannot make the sound index a string to compare as "if a == b .."
When I open the app, it shows me only two bottom buttons.. but not any image. How can I make it to show the first image?
I also like to make it a bit random think... When I click on "nextImage" button, I'd like to shows to different images but only one linked to the sound..so when I play the sound..had to check only the photo who matches with the sound.
At this moment, I have only 8 photos/sounds into the array, but when I click more than 9 times on nextImage.. the images are going on and on.. but the sound starts from beginning and it's not linked any more. for example, at the 10th image..it playSound says it's at 1. How can I make It to follow the image index?
How to convert the image index into text? for example, if its shows me the image "foto1"; I'd like to show me under the image a text in the label.
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var soundFiles: [String] = [
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"s8",
"s9"
]
var images1: [UIImage] = [
UIImage(named: "foto1.png")!,
UIImage(named: "foto2.png")!,
UIImage(named: "foto3.png")!,
UIImage(named: "foto4.png")!,
UIImage(named: "foto5.png")!,
UIImage(named: "foto6.png")!,
UIImage(named: "foto7.png")!,
UIImage(named: "foto8.png")!
]
var images2: [UIImage] = [
UIImage(named: "foto1.png")!,
UIImage(named: "foto2.png")!,
UIImage(named: "foto3.png")!,
UIImage(named: "foto4.png")!,
UIImage(named: "foto5.png")!,
UIImage(named: "foto6.png")!,
UIImage(named: "foto7.png")!,
UIImage(named: "foto8.png")!
]
var happySad: [UIImage] = [
UIImage(named: "sad.png")!,
UIImage(named: "happy.png")!
]
var currentImageIndex = 0
var currentImage2Index = 0
#IBOutlet weak var leftImage: UIImageView!
#IBOutlet weak var rightImage: UIImageView!
#IBOutlet weak var sh: UIImageView!
#IBAction func nextImages(_ sender: Any) {
currentImageIndex += 1
let numberOfImages = images1.count
let nextImage1Index = currentImageIndex % numberOfImages
leftImage.image = images1[nextImage1Index]
leftImage.isUserInteractionEnabled = true
self.view.addSubview(leftImage)
let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap1))
leftImage.addGestureRecognizer(gesture1)
currentImage2Index += 1
let numberOfImages2 = images2.count
let nextImage2Index = currentImage2Index % numberOfImages2
rightImage.image = images2[nextImage2Index]
sh.image = UIImage(named: "question")
rightImage.isUserInteractionEnabled = true
self.view.addSubview(rightImage)
let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap2))
rightImage.addGestureRecognizer(gesture2)
}
func singleTap1() {
if currentImageIndex == currentImage2Index {
sh.image = UIImage(named: "happy.png")
print("ok")
} else {
sh.image = UIImage(named: "sad.png")
print("not ok")
}
}
func singleTap2() {
if currentImageIndex == currentImage2Index {
sh.image = UIImage(named: "happy.png")
print("ok2")
} else {
sh.image = UIImage(named: "sad.png")
print("not ok2")
}
}
var player: AVAudioPlayer!
#IBAction func playSound(_ sender: Any) {
let numberOfImages = images1.count
let nextImage5Index = currentImageIndex % numberOfImages
let soundFilePath = Bundle.main.url(forResource: soundFiles[nextImage5Index], withExtension: ".m4a")!
player = try! AVAudioPlayer(contentsOf: soundFilePath)
player.prepareToPlay()
player.play()
}
}
I think you are over complicating the issue.
I would personally create a struct that contains each 'level' of the game.
enum correctImageType {
case left, right
}
struct Level {
var word: String
var leftImage: UIImage
var rightImage: UIImage
var soundFile: String
var correctImage: correctImageType
}
var level1 = Level(word: "Dog", leftImage: UIImage(named: "dog"), rightImage: UIImage(named: "cat", soundFile: "Woof", correctImage: .left)
This gives you enough information in one data structure to display each level. You can then create an array of these items, sort them, random sort them, mark as complete as each is done etc.
There are alot of questions within your question. I would try to make it more specific and tackle one particular part of the problem at a time. There is no problem in posting multiple questions as long as they are different.

iOS: Set setImageInputs of image slideshow to array of images

I'm using an image slideshow from here:
iconArr = [UIImage(named: "home-min")!,UIImage(named: "category-
min")!,UIImage(named: "settings-min")!,UIImage(named: "contact us-min")!,UIImage(named: "about us-min")!,UIImage(named: "logout")!]
I need to make this array as an image source.
for image in self.iconArr {
let img = image
self.SlideShow.setImageInputs([ImageSource(image: img)])
}
But that is not working, how can I do that?
you should try this way for sure, because you reset inputs in your for-loop
var imageSource: [ImageSource] = []
for image in self.iconArr {
let img = image
imageSource.append(ImageSource(image: img))
}
self.SlideShow.setImageInputs(imageSource)
As sooper stated, can be done this way
let imageSources = self.iconArr.map { ImageSource(image: $0) }
I found a solution from this url [https://stackoverflow.com/a/50461970/5628693][1]
Below is my code working fine :
var imageSDWebImageSrc = [SDWebImageSource]()
#IBOutlet weak var slideshow: ImageSlideshow!
Add below viewDidLoad()
slideshow.backgroundColor = UIColor.white
slideshow.slideshowInterval = 5.0
slideshow.pageControlPosition = PageControlPosition.underScrollView
slideshow.pageControl.currentPageIndicatorTintColor = UIColor.lightGray
slideshow.pageControl.pageIndicatorTintColor = UIColor.black
slideshow.contentScaleMode = UIViewContentMode.scaleAspectFill
// optional way to show activity indicator during image load (skipping the line will show no activity indicator)
slideshow.activityIndicator = DefaultActivityIndicator()
slideshow.currentPageChanged = {
page in
print("current page:", page)
}
let recognizer = UITapGestureRecognizer(target: self, action: #selector(Dashboard.didTap))
slideshow.addGestureRecognizer(recognizer)
} // now add below func
#objc func didTap() {
let fullScreenController = slideshow.presentFullScreenController(from: self)
// set the activity indicator for full screen controller (skipping the line will show no activity indicator)
fullScreenController.slideshow.activityIndicator = DefaultActivityIndicator(style: .white, color: nil)
}
And last step i was getting json data from below alamofire request
Alamofire.request(url, method: .post, parameters: data, encoding: JSONEncoding.default).responseJSON { response in
if(response.value == nil){
}
else {
let json2 = JSON(response.value!)
switch response.result {
case .success:
self.indicator.stopAnimating()
if let details = json2["imgs"].array {
for dItem in details {
let img = dItem["img"].stringValue
let image = SDWebImageSource(urlString: self.imgurl+img)
self.imageSDWebImageSrc.append(image!)
}
self.slideshow.setImageInputs(self.imageSDWebImageSrc)
}
break
case .failure( _):
break
}
}
}
Thanks dude :) happy coding

Increase/decrease brightness of image using UISlider?

I am building an iOS app which is based on image operations.
I want to increase and decrease brightness of image by slider value.
I have used this code to do this:
#IBOutlet var imageView: UIImageView!
#IBOutlet var uiSlider : UISlider!
override func viewDidLoad()
{
super.viewDidLoad()
var image = UIImage(named: "54715869.jpg")
imageView.image = image
uiSlider.minimumValue = -0.2
uiSlider.maximumValue = 0.2
uiSlider.value = 0.0
uiSlider.maximumTrackTintColor = UIColor(red: 0.1, green: 0.7, blue: 0, alpha: 1)
uiSlider.minimumTrackTintColor = UIColor.blackColor()
uiSlider.addTarget(self, action: "brightnesssliderMove:", forControlEvents: UIControlEvents.TouchUpInside)
uiSlider.addTarget(self, action: "brightnesssliderMove:", forControlEvents: UIControlEvents.TouchUpOutside)
}
func brightnesssliderMove(sender: UISlider)
{
var filter = CIFilter(name: "CIColorControls");
filter.setValue(NSNumber(float: sender.value), forKey: "inputBrightness")
var image = self.imageView.image
var rawimgData = CIImage(image: image)
filter.setValue(rawimgData, forKey: "inputImage")
var outpuImage = filter.valueForKey("outputImage")
imageView.image = UIImage(CIImage: outpuImage as CIImage)
}
Now my question is that when I increase slider value it also increase brightness of image but only when I change slider position for first time.
When I am again changing the position of slider I am getting this errror:
fatal error: unexpectedly found nil while unwrapping an Optional value.
This error is coming at line:
imageView.image = UIImage(CIImage: outpuImage as CIImage)
This time rawimgData data comes nil.
I found answer to my question here is how i have done coding.
import CoreImage
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var aCIImage = CIImage();
var contrastFilter: CIFilter!;
var brightnessFilter: CIFilter!;
var context = CIContext();
var outputImage = CIImage();
var newUIImage = UIImage();
override func viewDidLoad() {
super.viewDidLoad()
var aUIImage = imageView.image;
var aCGImage = aUIImage?.CGImage;
aCIImage = CIImage(CGImage: aCGImage)
context = CIContext(options: nil);
contrastFilter = CIFilter(name: "CIColorControls");
contrastFilter.setValue(aCIImage, forKey: "inputImage")
brightnessFilter = CIFilter(name: "CIColorControls");
brightnessFilter.setValue(aCIImage, forKey: "inputImage")
}
func sliderContrastValueChanged(sender: UISlider) {
contrastFilter.setValue(NSNumber(float: sender.value), forKey: "inputContrast")
outputImage = contrastFilter.outputImage;
var cgimg = context.createCGImage(outputImage, fromRect: outputImage.extent())
newUIImage = UIImage(CGImage: cgimg)!
imageView.image = newUIImage;
}
func sliderValueChanged(sender: UISlider) {
brightnessFilter.setValue(NSNumber(float: sender.value), forKey: "inputBrightness");
outputImage = brightnessFilter.outputImage;
let imageRef = context.createCGImage(outputImage, fromRect: outputImage.extent())
newUIImage = UIImage(CGImage: imageRef)!
imageView.image = newUIImage;
}
}
You can use AlamofireImage, here's an example of how you can do it:
#IBAction func brightnessChanged(sender: UISlider) {
let filterParameters = ["inputBrightness": sender.value]
imageView.image = originalImage.af_imageWithAppliedCoreImageFilter("CIColorControls", filterParameters: filterParameters)
}

Randomly select a UIImage

I need to pick one of these dots. I add them all before viewDidLoad, I need it to pick a random one. My current code returns the error cannot assign to 'openingScreenDynamicDot in 'self'. How is this fixed?
CODE:
let openingScreenDynamicDot = UIImage()
let dotOne = UIImage(named: "dot1.png")
let dotTwo = UIImage(named: "dot2.png")
let dotThree = UIImage(named: "dot3.png")
let dotFour = UIImage(named: "dot4.png")
let dotFive = UIImage(named: "dot5.png")
let dotSix = UIImage(named: "dot6.png")
let dotSeven = UIImage(named: "dot7.png")
let dotEight = UIImage(named: "dot8.png")
let dotNine = UIImage(named: "dot9.png")
let dotTen = UIImage(named: "dot10.png")
let dotEleven = UIImage(named: "dot11.png")
let dotTwelve = UIImage(named: "dot12.png")
let dotThirteen = UIImage(named: "dot13.png")
var imageNumber = arc4random()%13
override func viewDidLoad() {
let theRandomImages = [dotOne, dotTwo, dotThree, dotFour, dotFive, dotSix, dotSeven, dotEight, dotNine, dotTen, dotEleven, dotTwelve, dotThirteen]
openingScreenDynamicDot = theRandomImages.objectAtIndex(imageNumber)
}
You declare constants with the let keyword and variables with the var keyword.
So change let openingScreenDynamicDot to var openingScreenDynamicDot
also, a swift native array does not have a objectAtIndex method so..
change
openingScreenDynamicDot = theRandomImages.objectAtIndex(imageNumber)
to
openingScreenDynamicDot = theRandomImages[imageNumber]
You can try this code to generate one of your random "dots".
override func viewDidLoad(){
let openingScreenDynamicDot.image = UIImage(named: "dot\(arc4random_uniform(13) + 1).png")
}
This is called "String Interpolation". For more info, Click here.
I hope this can help you if you are still having problems.

Is there a way to check if a UIImage has been decompressed?

I'm sure most of you have dealt with forced decompression on a background thread to enhance rendering performance. My question is whether there is a way to check if an image has been decompressed.
It helped me to checked Image has been Decompressed or not by below technique. It is simple code to understand :-
import UIKit
class ViewController: UIViewController {
var compressedImage:NSString?
var decompressedImage:NSString?
override func viewDidLoad() {
super.viewDidLoad()
let image = compressImage()
var imageView = UIImageView(image: image)
//self.view.addSubview(imageView)
let decompressImage = deCompressImage(image: image)
let imageData = Data(UIImagePNGRepresentation(decompressImage)! )
print("***** Size after decompred \(imageData.description) **** ")
imageView = UIImageView(image: decompressImage)
decompressedImage = imageData.description as NSString?
let decompressed = checkImageBeenDecompressed(decompressedImage: decompressedImage!, compressedImage: compressedImage!)
print(decompressed)
//self.view.addSubview(imageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func checkImageBeenDecompressed(decompressedImage:NSString , compressedImage:NSString) -> Bool {
let decompressedSize = Int( decompressedImage.getNumFromString()! )
let compressedSize = Int (compressedImage.getNumFromString()! )
if( decompressedSize! > compressedSize! ) {
print("Image has been decompressed")
return true
}
print("Image has not been decompressed")
return false
}
func compressImage() -> UIImage {
let oldImage = UIImage(named: "background.jpg")
var imageData = Data(UIImagePNGRepresentation(oldImage!)! )
print("***** Original Uncompressed Size \(imageData.description) **** ")
imageData = UIImageJPEGRepresentation(oldImage!, 0.025)!
print("***** Compressed Size \(imageData.description) **** ")
compressedImage = imageData.description as NSString?
let image = UIImage(data: imageData)
return image!
}
func deCompressImage(image:UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(image.size, true, 0)
image.draw(at: CGPoint.zero)
let decompressedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return decompressedImage!
}
}
extension NSString {
func getNumFromString() -> String? {
var numberString: NSString?
let thisScanner = Scanner(string: self as String)
let numbers = NSCharacterSet(charactersIn: "0123456789")
thisScanner.scanUpToCharacters(from: numbers as CharacterSet, into: nil)
thisScanner.scanCharacters(from: numbers as CharacterSet, into: &numberString)
return numberString as? String;
}
}
Demo Reference

Resources