Swift中如何在UserDefaults保存和读取图片及旋转角度值?
Hey there! Let's break down your two Swift questions with clear, actionable solutions:
UserDefaults doesn't support storing UIImage directly, but we can convert images to Data (the raw binary representation) and store that instead. Here's how to do it:
Saving an Image
First, convert your UIImage to either PNG or JPEG data. PNG is lossless but results in larger files, while JPEG lets you adjust compression quality to balance size and clarity:
// Example: Save a UIImage named "myImage" if let imageData = myImage.pngData() { // Use jpegData(compressionQuality: 0.8) for JPEG UserDefaults.standard.set(imageData, forKey: "SavedUserImage") }
Reading the Saved Image
Retrieve the stored Data and convert it back to a UIImage:
if let savedImageData = UserDefaults.standard.data(forKey: "SavedUserImage"), let savedImage = UIImage(data: savedImageData) { // Assign the image to your UIImageView myImageView.image = savedImage }
Note: UserDefaults is meant for small pieces of data. If your image is large (e.g., high-resolution photos), it's better to save it to the app's document directory instead.
This is actually simpler than saving the image itself—you just need to store the rotation angle value (a numeric type) in UserDefaults, then apply it when your view loads. Here's how to integrate this into your existing code:
Save the Rotation Angle
When you set the rotation angle in your animation, save that value to UserDefaults right before or after the animation starts:
if totalVal == 250 || totalVal < 500 { let defaults = UserDefaults.standard let rotationAngle = CGFloat.pi * 0.40 // Your target angle // Save the angle to UserDefaults defaults.set(rotationAngle, forKey: "NeedleRotationAngle") UIView.animate(withDuration: 0.5, delay: 0.45, options: .curveEaseIn, animations: { self.needleImage.transform = CGAffineTransform(rotationAngle: rotationAngle) }, completion: nil) }
Restore the Angle on App Launch
Add this code to viewDidLoad() (or wherever your view initializes) to apply the saved angle when the app opens:
override func viewDidLoad() { super.viewDidLoad() // Read the saved angle—defaults to 0 if no value exists yet let savedAngle = CGFloat(UserDefaults.standard.double(forKey: "NeedleRotationAngle")) // Apply the saved rotation to your needle image needleImage.transform = CGAffineTransform(rotationAngle: savedAngle) }
Why this works: UserDefaults natively supports storing numeric types like Double, and since CGFloat can be converted to/from Double seamlessly, this is a reliable approach. If the user hasn't set the angle yet, double(forKey:) returns 0, so your needle starts at the default (unrotated) position.
内容的提问来源于stack exchange,提问作者Umair Ahmad

