Small size UIImageView display image becomes blurred

35 Views Asked by At

My picture will be blurred in a small size (153x153) UIImageView, but it will be displayed normally in another large size UIImageView (375x375) page, and i load the image using sd_setImageWithURL method. I can also see this when I zoom it in Chrome, this phenomenon can be seen in pictures of clothes with stripes.

blurred image

normal image

origin image url: https://images.ypcang.com/2023/07/10/515264AB9DAE6B765.jpg, https://images.ypcang.com/2023/07/10/916464AB9D91234ED.jpg

How to make it display normally in small size UIImageView

1

There are 1 best solutions below

0
DonMag On BEST ANSWER

This is called a "Moiré pattern" or "Moiré effect" - you can read about it here: https://en.wikipedia.org/wiki/Moiré_pattern ...

There are various things you can do to try to reduce the effect, but one easy setting may give you satisfactory results.

By default, a UIImageView uses "fast scaling" to get the best performance. We can change the .minificationFilter on the image view's layer like this:

imageView.layer.minificationFilter = .trilinear

Using your original 1200x1200 image in a 153x153 image view (which, on a @3x device results in a 459x459 pixel size), here's the difference:

enter image description here

Sample code to produce that (I downloaded your image and added it to assets as "sampleImage"):

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let origImage = UIImage(named: "sampleImage") else {
            fatalError("Could not load test image!!!")
        }

        let v1 = UIImageView()
        let v2 = UIImageView()
        
        [v1, v2].forEach { v in
            v.image = origImage
            v.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(v)
        }

        let targetSize: CGFloat = 153.0

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            
            v1.widthAnchor.constraint(equalToConstant: targetSize),
            v1.heightAnchor.constraint(equalTo: v1.widthAnchor),

            v2.widthAnchor.constraint(equalTo: v1.widthAnchor),
            v2.heightAnchor.constraint(equalTo: v1.heightAnchor),

            v1.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            v2.topAnchor.constraint(equalTo: v1.bottomAnchor, constant: 20.0),
            
            v1.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            v2.centerXAnchor.constraint(equalTo: g.centerXAnchor),

        ])

        // better results for bottom image view
        v2.layer.minificationFilter = .trilinear

    }
    
}