You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何在UserDefaults保存和读取图片及旋转角度值?

Hey there! Let's break down your two Swift questions with clear, actionable solutions:

1. Saving and Reading Images in UserDefaults

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.

2. Saving and Restoring Your Needle's Rotation Angle

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:07:36