본문 바로가기
iOS Swift/Today I Learned

이미지를 circle로 만들어주는 clipToBounds

by 호두빵 2022. 12. 22.

if let image: UIImage = ImageManager.shared.getImage(named: "myProfile.jpeg") {
    self.profileImage.image = image
    self.profileImage.clipsToBounds = true
    self.profileImage.layer.cornerRadius = self.profileImage.frame.height/2
    self.profileImage.layer.borderWidth = 1
    self.profileImage.layer.borderColor = UIColor.black.cgColor
}

 

프로필이미지를 저장까지는 했는데, 애써 예쁘게 만들어놓은 동그라미 모양이 아니라 이미지 그 자체... 사각형으로 나온다면 안되겠습니다. 이럴때일수록 침착함을 잃지 않고 방법이 없나 고민해봅니다. 이미 동그라미 모양으로 만들어져있으니 겉에 것만 뿌시면 되지 않을까..(?) 예를 들면 요즘에는 카페 같은 곳에서도 붕어빵을 많이 판매하는데요~ 바삭한 부분이 네모 모양으로 붕어의 주변을 감싼채로 판매되는 경우도 종종 보이더라구요. 이미지를 그 붕어빵이라고 가정하면, 저는 바삭한 테두리는 필요없고 붕어의 원형만 필요한 상태인 것입니다. 예시가 적합한 것 같지는 않지만 어쨌든 대충 아이디어는 그렇습니다. 찾아보니 cornerRadius를 이미지 프레임의 높이 절반값을 주면 팍팍 깎이게 되어서 결과적으로 4개의 각이 모두 적용이 되면 둥글게 보이는 효과를 줄 수 있다는 것을 알게 되었습니다. frame.height의 절반을 cornerRadius로 주는 것은 반지름의 원리를 생각하시면 좋은데,,글로 설명하기가 어렵네요. 애플 공식 문서를 찾아보니 아래와 같이 설명합니다.

 

The maximum corner radius is half the plane’s smaller dimension. For example, if a plane’s width and height properties are both 10.0, setting a corner radius of 5.0 gives the plane a circular shape, and increasing the corner radius beyond 5.0 has no effect. If a plane has width 10.0 and height 5.0, the maximum corner radius is 2.5, creating a rectangular shape with circular endcaps.

 

cornerRadius를 최대치로 적용해서, 동그랗게 만들기는 했는데, 이거까지만 한다면 여전히 뒷배경에 찜찜하게 남아있는 것들이 있을거에요. 왜냐하면 cornerRadius적용은 이미지의 bounds에 적용 되는 것이라서, clipsToBounds를 true로 설정해주지 않으면 안 됩니다. 내 눈으로 보여지는 이미지가 온전하게 동그랗기만 했으면 좋겠어! 한다면 이미지의 clipToBounds를 true로 설정해야 합니다. 

 

참고 문서는 아래와 같습니다.

 

https://developer.apple.com/documentation/scenekit/scnplane/1523005-cornerradius

 

Apple Developer Documentation

 

developer.apple.com

 

https://fluffy.es/rounded-corner-shadow

 

How to implement rounded corner image view with shadow

Rushing a project and no time to read explanation? Jump to the answer code Since iOS 11, the App Store app has adopted card UI like this : The card-like UI has rounded corner and a light drop shadow beneath it, how can we achieve it? Say we have a image

fluffy.es