2017-12-19 14 views
1

UIImageView의 경우 가로 채우기 콘텐츠 모드를 사용하고 있습니다. 괜찮습니다. 그러나 일부 이미지의 경우에는 clipsToBounds = true을 사용했기 때문에 이미지가 위쪽에서 잘립니다. 그래서 여기 내가 원하는 것입니다 : 내가 예를 들어, 동시에 두 개의 필터를 활성화하려면 :UIImageView의 상단 컨텐츠 모드와 결합 된 애스펙트 채우기 컨텐츠 모드를 사용할 수 있습니까?

여기

내가 화면 채우기로 설정된 이미지이다 :

image view with the aspect fill content mode

.. .and 이미지보기 나는 contentMode = .top를 사용하여 설정 :

image view with the top content mode

그래서 나는이 두 가지 내용 모드를 병합 할. 가능한가? 미리 감사드립니다.

+0

가 '병합'을 정의합니다. –

+0

ImageView에서 콘텐츠 모드를 모두 사용하고 싶습니다. 가능한가? –

+0

@ V-Dev. u 이미지의 상단 또는 가운데 부분 만 채우기를 원합니다. –

답변

3

이미지보기의 너비가 있지만 가로 세로 비율을 유지하도록 이미지의 크기를 조정해야합니다. 그런 다음 이미지보기의 콘텐츠 모드를 .top으로 설정하고 범위로 클리핑을 사용 설정합니다.

resizeImage 기능은 this answer의 수정 된 버전입니다.

func setImageView() { 
    imageView.contentMode = .top 
    imageView.clipsToBounds = true 
    let image = UIImage(named: "portrait") 
    imageView.image = resizeImage(image, newWidth: imageView.frame.width) 
} 

func resizeImage(_ image: UIImage?, newWidth: CGFloat) -> UIImage? { 
    guard let image = image else { 
     return nil 
    } 

    let scale = newWidth/image.size.width 
    let newHeight = image.size.height * scale 

    let newSize = CGSize(width: newWidth, height: newHeight) 

    UIGraphicsBeginImageContext(newSize) 
    image.draw(in: CGRect(origin: .zero, size: newSize)) 
    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    return newImage 
} 
+0

고마워, 내가 원한 거의 작동합니다. –

0

이 시도 :

imageView.contentMode = UIViewContentModeTop; 
imageView.image = [UIImage imageWithCGImage:image.CGImage scale:image.size.width/imageView.frame.size.width orientation:UIImageOrientationUp]; 
+0

@ the4kman 주어진 답과 같은 결과를 표시합니다. 그러나 그것은 더 짧습니다. :) –

+0

네, 같은 결과 :) –