티스토리 뷰


info.plist 파일에서 Add Row를 해주세요.


ViewController 파일에서 UIImageView를 extension해주세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import UIKit
 
extension UIImageView {
    func downloadImageFrom(_ link:String, contentMode: UIViewContentMode) {
        URLSession.shared.dataTask( with: URL(string:link)!, completionHandler: {
            (data, response, error) -> Void in
            DispatchQueue.main.async {
                self.contentMode =  contentMode
                if let data = data { self.image = UIImage(data: data) }
            }
        }).resume()
    }
    
    func downloadAndResizeImageFrom(_ link:String, contentMode: UIViewContentMode ,newWidth:CGFloat) {
        URLSession.shared.dataTask( with: URL(string:link)!, completionHandler: {
            (data, response, error) -> Void in
            DispatchQueue.main.async {
                self.contentMode =  contentMode
                if let data = data {
                    if let tempImage = UIImage(data: data){
                        let scale = newWidth / tempImage.size.width
                        let newHeight = tempImage.size.height * scale
                        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
                        tempImage.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
                        let newImage = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()
                        self.image = newImage
                    }
                }
            }
        }).resume()
    }
}
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.setImageView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setImageView(){
        let frame = self.view.frame
        let urlImageImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height/2))
        let urlResizedImageView = UIImageView(frame: CGRect(x: 0, y: frame.height/2, width: frame.width, height: frame.height/2))
        
        urlImageImageView.downloadImageFrom("https://t1.daumcdn.net/cfile/tistory/211BA94656A867BA37", contentMode: .scaleToFill)
        urlResizedImageView.downloadAndResizeImageFrom("https://t1.daumcdn.net/cfile/tistory/211BA94656A867BA37", contentMode: .scaleToFill, newWidth: 50)
        
        self.view.addSubview(urlImageImageView)
        self.view.addSubview(urlResizedImageView)
    }
}
 
cs


댓글
댓글쓰기 폼