Retrieving Uiimage from Uiimageview in Swift

take uiimageview image and convert to uiimage (swift4)

You have

var image = UIImage(named: self.imageV)

That won't compile, because imageV is an image view, not the (string) name of an image in your bundle.

Just say

var image = self.imageV.image

convert uiimage view to uiimage

You cannot convert UIImageView to UIImage, but you can use the image from the UIImageView:

let image: UIImage = yourImageView.image

How to retrieve saved UIImageViews from documents folder in Swift?

You can retrieve it like this

func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage? {

let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
if let image = UIImage(contentsOfFile: imageURL.path) {
return image

} else {
print("image not found")

return nil
}
}
return nil
}

And for saving

func saveImageToDocumentDirectory(image: UIImage , imageName: String) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = imageName // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = image.jpegData(compressionQuality: 1),
!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}

How to get x and y position of UIImage in UIImageView?

Use following extension

extension UIImageView {

var imageRect: CGRect {
guard let imageSize = self.image?.size else { return self.frame }

let scale = UIScreen.main.scale

let imageWidth = (imageSize.width / scale).rounded()
let frameWidth = self.frame.width.rounded()

let imageHeight = (imageSize.height / scale).rounded()
let frameHeight = self.frame.height.rounded()

let ratio = max(frameWidth / imageWidth, frameHeight / imageHeight)
let newSize = CGSize(width: imageWidth * ratio, height: imageHeight * ratio)
let newOrigin = CGPoint(x: self.center.x - (newSize.width / 2), y: self.center.y - (newSize.height / 2))
return CGRect(origin: newOrigin, size: newSize)
}

}

Usage

let rect = imageView.imageRect
print(rect)

UI Test

let testView = UIView(frame: rect)
testView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
imageView.superview?.addSubview(testView)


Related Topics



Leave a reply



Submit