ContentMode changes in uiimageview after draw

2019-08-14 07:57发布

I have been following Ray Wenderlics's tutorial on how to create a basic draw app.

Ive got it working perfectly except for when I draw the content mode changes on the uiimageview.

I've set it to aspectFill in storyboard and applied an image

I think the problem is in my touches ended method

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
        // draw a single point
        drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }

    // Merge tempImageView into mainImageView
    UIGraphicsBeginImageContext(mainImageView.frame.size)
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: CGBlendMode.normal, alpha: 1.0)
    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: CGBlendMode.normal, alpha: opacity)
    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    tempImageView.image = nil


}

it changes the content mode to what appears to be scaleToFill or Scale to fit?

Does anybody know how I change this?

regards

Thomas

Update

Thanks Matt for your direction

Ive added the following code

  let imageSize = AVMakeRect(aspectRatio: (mainImageView.image?.size)!, insideRect: mainImageView.frame)

    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: imageSize.width , height: imageSize.height), blendMode: CGBlendMode.normal, alpha: 1.0)
    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), blendMode: CGBlendMode.normal, alpha: opacity)
    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()

I think I'm on the right track but the image is now resizing to aspect fit rather then aspect fill.

1条回答
贪生不怕死
2楼-- · 2019-08-14 08:08

The content mode of the image view is not changing. (You can test that easily, just by examining its contentMode, which doesn't happen anywhere in your code.)

The problem is the way you draw! You are drawing an image, mainImageView.image, into a rect CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height). That stretches the image to fit that rect exactly — resulting in the stretching behavior that you're complaining about.

In other words, you are saying "Scale this image to fill this rect", and that's exactly what's happening.

查看更多
登录 后发表回答