I have two views stacked on top of each other. The first view is called “containerView” and contains information about a person. The second view is called “profileImageView” and displays the person’s image.
Initially, only containerView is visible. However, when the user clicks on the “Reveal Face” button, profileImageView is displayed and containerView is hidden. I want to display the profileImageView with a puzzle effect, gradually revealing the entire image.
I want to gradually reveal an image by starting with random puzzle pieces.
var puzzlePieces = [UIView]()
override func viewDidLoad() {
super.viewDidLoad()
self.setUpPuzzleView()
}
func setUpPuzzleView() {
self.profileImageView.image = UIImage(named: "photo")
// Break the face image into puzzle pieces and scatter them randomly
for row in 0..<4 {
for column in 0..<4 {
let pieceWidth = self.profileImageView.bounds.width / 4
let pieceHeight = self.profileImageView.bounds.height / 4
let pieceFrame = CGRect(
x: CGFloat(column) * pieceWidth,
y: CGFloat(row) * pieceHeight,
width: pieceWidth,
height: pieceHeight
)
let puzzlePiece = UIView(frame: pieceFrame)
puzzlePiece.layer.contents = cropImage(image: self.profileImageView.image!, rect: pieceFrame).cgImage
puzzlePiece.isHidden = true
profileImageView.addSubview(puzzlePiece)
puzzlePieces.append(puzzlePiece)
// Randomly scatter puzzle pieces
let randomXOffset = CGFloat.random(in: -100...100)
let randomYOffset = CGFloat.random(in: -100...100)
puzzlePiece.transform = CGAffineTransform(translationX: randomXOffset, y: randomYOffset)
}
// MARK: - Crop Image
func cropImage(image: UIImage, rect: CGRect) -> UIImage {
let scale = image.scale
let croppedRect = CGRect(
x: rect.origin.x * scale,
y: rect.origin.y * scale,
width: rect.size.width * scale,
height: rect.size.height * scale
)
if let croppedCGImage = image.cgImage?.cropping(to: croppedRect) {
return UIImage(cgImage: croppedCGImage, scale: scale, orientation: image.imageOrientation)
}
return UIImage()
}
// MARK: - IBActions
@IBAction func onRevealPhoto(_ sender: UIButton) {
UIView.animate(withDuration: 1.0) {
self.containerView.isHidden = true
self.profileImageView.isHidden = false
for puzzlePiece in self.puzzlePieces {
puzzlePiece.transform = .identity
puzzlePiece.isHidden = false // Reveal puzzle pieces
}
}
}
I have successfully created puzzle pieces. see image link: https://ibb.co/F7LfKwB
The issue I’m facing is after clicking on button, a whole new view is created on my profileImageView with some top-right corner radius. see image link: https://ibb.co/J7YrhFN
Any Kind of help would be highly appreciated!
Thank You!




