Search code examples
swiftnsarray

How to create array of images, and use draw() to draw them out in Swift?


I am trying to figure out how to create a 'map' using an array of images. I can draw out one image fine using f.draw(at:imagePoint) , but when I try to draw out an array of the images, I am not able to. How do I set up the array of images, and then draw out the array that I have specified?

  var loc = CGPoint(x: 50, y:30)
    //variables to hold the separate pictures
    let f = UIImage(named: "forest.png")!
    var m = UIImage(named: "mountain.png")!
    let o = UIImage(named: "out.png")!
    let p = UIImage(named: "plain.png")!
    let t = UIImage(named: "treasure.png")!
    let w = UIImage(named: "water.png")!
    let person = UIImage(named: "person.png")!

    override func draw(_ rect: CGRect) {

        //create array of the referenced images
        let tileMap = [o,o,o,o,o,o,o,o,o,o,o,o,
                       o,m,m,f,f,f,p,p,p,p,w,o,
                       o,m,m,f,f,f,p,p,p,p,w,o,m]

        print("draw called")
        var imagePoint = CGPoint(x: 0,y: 0)
        //display map
        //tileMap.draw(at: imagePoint)

        for element in tileMap{
            element.draw(at: imagePoint)
            //imagePoint = CGPoint(x:0,y:0)
            //how to increment CGPoint for each image?

        }

        //display person
        person.draw(at:loc)
    }

Solution

  • may be this can be help full to you :=

        let tileMap = [o,o,o,o,o,o,o,o,o,o,o,o,
                       o,m,m,f,f,f,p,p,p,p,w,o,
                       o,m,m,f,f,f,p,p,p,p,w,o,m]
    
        print("draw called")
    
        let row = 5
    
        let numberOfInRow = tileMap.count / row
    
        let xWidth = Int(UIScreen.main.bounds.width) / numberOfInRow
        let yHeight = Int(UIScreen.main.bounds.height) / row
    
        var xPoint = 0
        var yPoint = 0
    
        var itemCountInRow = 0
    
        for element in tileMap{
    
            let imagePoint = CGPoint(x: xPoint,y: yPoint)
            element.draw(at: imagePoint)
    
            if(numberOfInRow > itemCountInRow){
                itemCountInRow += 1
                xPoint += xWidth
            }else{
                itemCountInRow = 0
                xPoint = 0
                yPoint += yHeight
            }
        }