Reputation: 381
According to my requirement i need to check UIView
are placed inside of UIImage
portion or not.Suppose i have UIImage
of human with cap, here i need to check my view placed inside of cap portion or not.
Could you please guide me to achieve following requirement.
---------------------------------
| |
| UIImage |
| -------------------------- |
| | Image portion | |
| | ------ | |
| | | view | | |
| | ------ | |
| | | |
| -------------------------- |
| |
| |
--------------------------------
Upvotes: 10
Views: 399
Reputation: 16436
You have already got idea that how to check that two CGRect is overlapping or not. with @Mario's answer.
Question is how you can get image size from imageView which is
AVMakeRect(aspectRatio: myImage.size, insideRect: sampleImageView.frame)
But one more thing you need to take care about contains(_:)
or intersects(_:)
of CGRect
is that both should have same superview. like
Main( UIView) -> UIImageView
and
Main( UIView) -> UIView(that need to be checked)
If this condition is not applying with your view hierarchy you have options to convert rect using
1) convertRect:fromView:
Docs
2) convertRect:toView
Docs
Hope it is helpful
Upvotes: 0
Reputation: 2122
In fact, it's built-in since iOS 4 (for UIViewContentModeScaleAspectFit):
@import AVFoundation;
AVMakeRectWithAspectRatioInsideRect(imageView.image.size, imageView.bounds);
Since frame components may be not round numbers, consider wrapping the call by
CGRectIntegral(…)
see https://nshipster.com/image-resizing/ for more info.
Upvotes: 0
Reputation: 539
import AVFoundation
Get Rect For image View and Convert rect as per image size using AVMakeRect.
Check new rect contain UIView frame using contains method of coordinate system
Code :
import UIKit
import AVFoundation
func containViewInSideImage(imgView:UIImageView,innerView:UIView) -> Bool {
let size = imgView.image?.size // size of image
let imageRect = AVMakeRect(aspectRatio: size!, insideRect: imgView.frame) // rect of image portion
return imageRect.contains(innerView.frame) // check view is inside image rect
}
Note : Above code will work for aspect-fit property of image view and Make Sure imageView and view both are belong to same supper view otherwise need to convert rect
Upvotes: 0
Reputation: 459
You could use the method contains(_:)
or intersects(_:)
of CGRect
.
Your code will look something like
let imagePortionFrame = CGRect(....) // some rect based on your image view
imagePortionFrame.contains(view.frame)
You just need to make sure that the coordinates of imagePortionFrame
and view.frame
are expressed using the same coordinate system; if not you could use the method convert(_:to:)
Reference:
Upvotes: 3