preneond
preneond

Reputation: 531

iOS - Layout UIImageView's subview on the scaleaspectfit UIImageView's image

I have UITableView, where is a UIStackView with same views(different content only) on each cell.(The tableView's cell is shown below)

UITableView cell

The view consists of UIImageView and UILabel above. The UIImageView's content is set to .scaleAspectFit, because of keeping ratio. I have a problem with adding a new image layer (subview) to imageView, which has to perfectly overlap current image, but I can't fit on image properly with autolayout, because I know only UIImageView's anchor, not image's anchor (it doesn't exists).

PS: I have tried to use imageview.image.size.width, to set width and height, but it's also useless.

Current code of adding subview using autolayout:

func addStripe(){
        let stripeLayer = UIImageView(image: #imageLiteral(resourceName: "book_new"))
        imageView.addSubview(stripeLayer)

        stripeLayer.contentMode = .scaleToFill
        stripeLayer.translatesAutoresizingMaskIntoConstraints = false

        stripeLayer.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
        stripeLayer.leadingAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
        stripeLayer.trailingAnchor.constraint(equalTo: imageView.trailingAnchor).isActive = true

Aaaand there is a result of addStripe function (the wrong one)

And there is a result

Thanks everyone for your time!

Upvotes: 0

Views: 506

Answers (2)

preneond
preneond

Reputation: 531

@ReinhardManner's comment helped me and it works. This single line fix my problem

let sizeInView = AVMakeRect(aspectRatio: imgViewFake.image.size, insideRect: imgViewFake.bounds).size

Upvotes: 0

p.yarandi
p.yarandi

Reputation: 59

I think you should set frame of your stripeLayer equal to imageView. You can do this with init method of UIImageView like this:

let stripeLayer = UIImageView(frame: imageView.frame)
stripeLayer.image = #imageLiteral(resourceName: "book_new")
imageView.addSubview(stripeLayer.image)

I hope it help you

Upvotes: 1

Related Questions