見出し画像

Swiftで画像を表示させよう(簡単コピペ)


Swiftで画像を表示させましょう。

完成はこんな感じです。

画像6


環境


MacBook Air  M1
Swift
Xcode​



Swiftで画像を表示させましょう。



まずは、プロジェクトを立ち上げて、Assets.xcassetsを選択

画像1


すると、下記のようにAppiconなどが表示されます。この部分に表示させたい画像を追加します。

追加の仕方はFinderをクリックしたらフォルダが表示されるので、その中から画像を選びドラッグ&ドロップ。

画像2



そしたら左側のViewController.Swiftをクリック。するとこのような画面になります。

画像3



import UIKit

class ViewController: UIViewController {

   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       initImageView()      ←ここが重要
   }


上にある

 // Do any additional setup after loading the view.

と、

}

の間に

initImageView() 

を追記



そしてこのCodeをまるまるコピペしてみてください


   
   private func initImageView(){
      
       let image1:UIImage = UIImage(named:"(ここに表示させたい画像の名前)")!
       
      
       let imageView = UIImageView(image:image1)
       
     
       let screenWidth:CGFloat = view.frame.size.width
       let screenHeight:CGFloat = view.frame.size.height
       
     
       let imgWidth:CGFloat = image1.size.width
       let imgHeight:CGFloat = image1.size.height
       
      
       let scale:CGFloat = screenWidth / imgWidth
       let rect:CGRect =
           CGRect(x:0, y:0, width:imgWidth*scale, height:imgHeight*scale)
       
      
       imageView.frame = rect;
       
       
       imageView.center = CGPoint(x:screenWidth/2, y:screenHeight/2)
       
     
       self.view.addSubview(imageView)
       
       
   }
   


コピペしたCodeを

import UIKit

class ViewController: UIViewController {

   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       initImageView()      ←ここが重要
   }


先ほど追記した  }の下にペーストしましょう。

Codeが間違ってなかったらこのように表示されます。

画像5



完成コード画像です。

画像4


全Code

import UIKit

class ViewController: UIViewController {

   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       initImageView()     
   }
   
   
   
   private func initImageView(){
      
       let image1:UIImage = UIImage(named:"(ここに表示させたい画像の名前)")!
       
      
       let imageView = UIImageView(image:image1)
       
     
       let screenWidth:CGFloat = view.frame.size.width
       let screenHeight:CGFloat = view.frame.size.height
       
     
       let imgWidth:CGFloat = image1.size.width
       let imgHeight:CGFloat = image1.size.height
       
      
       let scale:CGFloat = screenWidth / imgWidth
       let rect:CGRect =
           CGRect(x:0, y:0, width:imgWidth*scale, height:imgHeight*scale)
       
      
       imageView.frame = rect;
       
       
       imageView.center = CGPoint(x:screenWidth/2, y:screenHeight/2)
       
     
       self.view.addSubview(imageView)
       
       
   }
   
  

この記事が気に入ったらサポートをしてみませんか?