2017-04-12 1 views
-1

나는 엑스 코드가 나에게 전화를 허용하지 않습니다 그러나 나는 아래있는 UIImage

let logoView: UIImageView = { 
    let LV = UIImageView() 
    let thumbnail = resizeImage(image: "DN", CGSize.init(width:70, height:70)) 
    LV.image = thumbnail 
    LV.contentMode = .scaleAspectFill 
    LV.layer.masksToBounds = true 
    return LV 
}() 

같은 확장을 호출하여 이미지 크기를 조정하려고

extension UIImage { 

    func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { 
     let size = image.size 

     let widthRatio = targetSize.width/image.size.width 
     let heightRatio = targetSize.height/image.size.height 

     // Figure out what our orientation is, and use that to form the rectangle 
     var newSize: CGSize 
     if(widthRatio > heightRatio) { 
      newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) 
     } else { 
      newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) 
     } 

     // This is the rect that we've calculated out and this is what is actually used below 
     let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) 

     // Actually do the resizing to the rect using the ImageContext stuff 
     UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) 
     image.draw(in: rect) 
     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return newImage! 
    } 
} 

이있는 UIImage 크기 조정 확장자가 크기 조정 함수 확장. 이미지의 크기를 올바르게 조정하려면 어떻게해야합니까?

func setupViews() { 


    addSubview(logoView) 
    } 
+0

http://stackoverflow.com/questions/31314412/how-to-

이 함수는 다음과 같이해야한다, 해결하려면 크기 조정 - 이미지 - 신속한 –

답변

2

확장 기능은 독립 실행 형 기능이 아니라 확장 기능에 연결됩니다. 귀하의 경우에는 UIImage에 함수를 추가하고 있지만 독립형 함수처럼 호출하고 있습니다. 좋아

extension UIImage { 

    func resizeImage(targetSize: CGSize) -> UIImage { 
     // the image is now “self” and not “image” as you original wrote 
     ... 
    } 
} 

당신은 그것을 부를 것이다 : :

let logoView: UIImageView = { 
    let LV = UIImageView() 
    let image = UIImage(named: "DN") 
    if let image = image { 
     let thumbnail = image.resizeImage(CGSize.init(width:70, height:70)) 
     LV.image = thumbnail 
     LV.contentMode = .scaleAspectFill 
     LV.layer.masksToBounds = true 
    } 
    return LV 
}() 
+0

자체에서 이미지를 참조 할 수있는 기능에 – muescha

+1

좋은 지적, 나는 그것을 반영하기 위해 내 대답을 편집합니다. 고마워요 @ muescha –

+0

대답 주셔서 감사합니다하지만 난 여전히 작동하도록 할 수 없습니다. 내가 진술 한대로 선언했지만 로고보기 내부에서 작업 할 수는 없습니다. 또한 UIImageView UIImageView 로고보기 재정의하지만 하위 뷰로 UIImage 추가 할 수 없습니다. UIImageView 내에서 호출하는 방법 또는 구현할 수있는 다른 방법은 무엇입니까? – Ola