티스토리 뷰
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 |
'IOS - SWIFT' 카테고리의 다른 글
SWIFT 3 - 포스터치 사용하기 (Force Touch,UIPreviewInteraction) (0) | 2016.10.30 |
---|---|
SWIFT 3 - UILabel 글자 크기 부분 변경(Changing font size inside label) (0) | 2016.10.30 |
IOS SWIFT 절댓값 구하기 (abs) (0) | 2016.08.28 |
IOS SWIFT 소스코드로 스토리보드에서 UIViewController 불러오기 (load UIViewController programmatically from storyboard) (0) | 2016.08.02 |
IOS SWIFT PHAsset을 이미지로 만들기 (PHAsset, UIImage, PHAsset to UIImage) (0) | 2016.06.29 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday