Trouble converting custom CGRect function from Objective-C to Swift - swift

I've been going back and forth on trying to convert a custom CGRect function from Objective-C to Swift.
I'll make some small progress but then I always end up getting stuck. Here is the working function in Objective-C:
CGRect CGRectSmallestWithCGPoints(NSMutableArray *pointsArray, int numberOfPoints) {
NSValue *firstValue = pointsArray[0];
CGFloat greatestXValue = [firstValue CGPointValue].x;
CGFloat greatestYValue = [firstValue CGPointValue].y;
CGFloat smallestXValue = [firstValue CGPointValue].x;
CGFloat smallestYValue = [firstValue CGPointValue].y;
for(int i = 1; i < numberOfPoints; i++) {
NSValue *value = pointsArray[i];
CGPoint point = [value CGPointValue];
greatestXValue = MAX(greatestXValue, point.x);
greatestYValue = MAX(greatestYValue, point.y);
smallestXValue = MIN(smallestXValue, point.x);
smallestYValue = MIN(smallestYValue, point.y);
}
CGRect rect;
rect.origin = CGPointMake(smallestXValue, smallestYValue);
rect.size.width = greatestXValue - smallestXValue;
rect.size.height = greatestYValue - smallestYValue;
return rect;
}
Here's where I currently am with the Swift conversion:
func CGRectSmallestWithCGPoints(pointsArray: NSArray, numberOfPoints: Int) -> CGRect {
var greatestXValue = pointsArray[0].x
var greatestYValue = pointsArray[0].y
var smallestXValue = pointsArray[0].x
var smallestYValue = pointsArray[0].y
for(var i = 1; i < numberOfPoints; i++)
{
let point = pointsArray[i];
greatestXValue = max(greatestXValue, point.x);
greatestYValue = max(greatestYValue, point.y);
smallestXValue = min(smallestXValue, point.x);
smallestYValue = min(smallestYValue, point.y);
}
var rect = CGRect()
rect.origin = CGPointMake(smallestXValue, smallestYValue);
rect.size.width = greatestXValue - smallestXValue;
rect.size.height = greatestYValue - smallestYValue;
return rect;
}
The errors start in the for loop. When I try to use max and min it gives me the following error:
Cannot assign a value of type 'CLHeadingComponentValue' (aka 'Double') to a value of type 'CLHeadingComponentValue!'
And then after the for loop when I modify the rect values it gives me a similar error:
Cannot assign a value of type 'CLHeadingComponentValue' (aka 'Double') to a value of type 'CGFloat'
I'm having trouble understanding why this conversion seems so hard. I've been using Swift on and off for the past few weeks now and I've gotten stuck on certain things like some of the optional concepts but never been stuck on something for this long before.
I'm using Xcode 7 beta with Swift 2 and would really appreciate your help thanks.

You have some mistakes in your code, you have to use the CGPointValue property instead of the x property directly see the fixed code:
func CGRectSmallestWithCGPoints(pointsArray: NSArray, numberOfPoints: Int) -> CGRect {
var greatestXValue: CGFloat = pointsArray[0].CGPointValue.x
var greatestYValue: CGFloat = pointsArray[0].CGPointValue.y
var smallestXValue: CGFloat = pointsArray[0].CGPointValue.x
var smallestYValue: CGFloat = pointsArray[0].CGPointValue.y
for(var i = 1; i < numberOfPoints; i++) {
let point = pointsArray[i].CGPointValue
greatestXValue = max(greatestXValue, point.x)
greatestYValue = max(greatestYValue, point.y)
smallestXValue = min(smallestXValue, point.x)
smallestYValue = min(smallestYValue, point.y)
}
var rect = CGRect()
rect.origin = CGPointMake(smallestXValue, smallestYValue);
rect.size.width = greatestXValue - smallestXValue;
rect.size.height = greatestYValue - smallestYValue;
return rect
}
I hope this help you.

A more functional approach:
func CGRectSmallestWithCGPoints(pointsArray: [CGPoint]) -> CGRect? {
if pointsArray.isEmpty {
return nil
}
let minX = pointsArray.reduce(CGFloat.max) { min, point in min(min, point.x) }
let minY = pointsArray.reduce(CGFloat.max) { min, point in min(min, point.y) }
let maxX = pointsArray.reduce(CGFloat.min) { max, point in max(max, point.x) }
let maxY = pointsArray.reduce(CGFloat.min) { max, point in max(max, point.y) }
let rect = CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
return rect
}

Related

Convert for loop from Objective-C

I am trying to convert an old Objective-C code into Swift, however I cannot find the way to make this for loop to work without errors. How could this be converted into Swift?
for var y = 0; y < columns; y++ { //C-style for statement is deprecated and will be removed in a future version of Swift
xPos = 0.0
for var x = 0; x < rows; x++ { //C-style for statement is deprecated and will be removed in a future version of Swift
var rect: CGRect = CGRectMake(xPos, yPos, width, height)
var cImage: CGImageRef = CGImageCreateWithImageInRect(image.CGImage, rect)!
var dImage: UIImage = UIImage(CGImage: cImage)
var imageView: UIImageView = UIImageView(frame: CGRectMake(x * width, y * height, width, height))
imageView.image = dImage
imageView.layer.borderColor = UIColor.blackColor().CGColor
imageView.layer.borderWidth = 1.0
//self.view!.addSubview(imageView)
arrayImages.append(dImage)
xPos += width
}
yPos += height
}
In your case, this should do it.
for y in 0..<columns {
for x in 0..<rows {
// do what you want with x and y
}
}

Zig zac path in sprite kit

I want the sprite kit node to move 200 px to the right and 400px to left and then again 400px to right and so on until leaves the screen
var cgpath: CGMutablePathRef = CGPathCreateMutable();
// random values
var xStart: CGFloat = CGFloat(0.0);
var xEnd: CGFloat = CGFloat(0.0);
// ControlPoint1
var cp1X: CGFloat = CGFloat(200.0);
var cp1Y: CGFloat = CGFloat(400.0);
// ControlPoint2
var cp2X: CGFloat = CGFloat(200.0);
var cp2Y: CGFloat = CGFloat(280.0);
var s: CGPoint = CGPointMake(xStart,-self.frame.size.height/2);
var e: CGPoint = CGPointMake(xEnd, self.frame.size.height/2);
var cp1: CGPoint = CGPointMake(cp1X, cp1Y);
var cp2: CGPoint = CGPointMake(cp2X, cp2Y);
CGPathMoveToPoint(cgpath,nil, s.x, s.y);
CGPathAddCurveToPoint(cgpath, nil, cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);
var ball:SKSpriteNode = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(40, 40));
var followTrack = SKAction.followPath(cgpath, asOffset: false, orientToPath: true, duration: 15.0);
var forever: SKAction = SKAction.repeatActionForever(followTrack);
ball.runAction(forever);
self.addChild(ball);
let shapeNode = SKShapeNode(path: cgpath)
self.addChild(shapeNode);
Try the following code to get a zig zag path using bezier curves.
var cgpath: CGMutablePathRef = CGPathCreateMutable();
var xStart: CGFloat = CGFloat(200.0);
var xEnd: CGFloat = CGFloat(200.0);
var yStart : CGFloat = 0
var yEnd : CGFloat = self.size.height
let numberOfIntermediatePoints = 10
let xOffset : CGFloat = 400
let intervalY = (yEnd - yStart)/CGFloat(numberOfIntermediatePoints)
var s: CGPoint = CGPointMake(xStart,yStart);
CGPathMoveToPoint(cgpath,nil, s.x, s.y);
for i in stride(from: 0, through: numberOfIntermediatePoints - 1, by: 1) {
let yOff = intervalY * CGFloat(i) + yStart
let controlPointInterval = intervalY/3
var cp1X: CGFloat = CGFloat(xStart + xOffset);
var cp1Y: CGFloat = CGFloat(yStart + yOff + controlPointInterval);
var cp2X: CGFloat = CGFloat(xStart - xOffset);
var cp2Y: CGFloat = CGFloat(yStart + yOff + controlPointInterval * 2);
var e: CGPoint = CGPointMake(xEnd, yStart + yOff + intervalY);
var cp1: CGPoint = CGPointMake(cp1X, cp1Y);
var cp2: CGPoint = CGPointMake(cp2X, cp2Y);
CGPathAddCurveToPoint(cgpath, nil, cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);
}
var ball:SKSpriteNode = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(40, 40));
var followTrack = SKAction.followPath(cgpath, asOffset: false, orientToPath: true, duration: 5.0);
var forever: SKAction = SKAction.repeatActionForever(followTrack);
ball.runAction(forever);
self.addChild(ball);
let shapeNode = SKShapeNode(path: cgpath)
self.addChild(shapeNode);
Change numberOfIntermediatePoints and xOffset values to change the number of zig zags and the amount of distance moved in each zig zag.

targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout

I've got a very simple collectionView in my app (just a single row of square thumbnail images).
I'd like to intercept the scrolling so that the offset always leaves a full image at the left side. At the moment it scrolls to wherever and will leave cut off images.
Anyway, I know I need to use the function
- (CGPoint)targetContentOffsetForProposedContentOffset:withScrollingVelocity
to do this but I'm just using a standard UICollectionViewFlowLayout. I'm not subclassing it.
Is there any way of intercepting this without subclassing UICollectionViewFlowLayout?
Thanks
OK, answer is no, there is no way to do this without subclassing UICollectionViewFlowLayout.
However, subclassing it is incredibly easy for anyone who is reading this in the future.
First I set up the subclass call MyCollectionViewFlowLayout and then in interface builder I changed the collection view layout to Custom and selected my flow layout subclass.
Because you're doing it this way you can't specify items sizes, etc... in IB so in MyCollectionViewFlowLayout.m I have this...
- (void)awakeFromNib
{
self.itemSize = CGSizeMake(75.0, 75.0);
self.minimumInteritemSpacing = 10.0;
self.minimumLineSpacing = 10.0;
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.sectionInset = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
}
This sets up all the sizes for me and the scroll direction.
Then ...
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGFloat offsetAdjustment = MAXFLOAT;
CGFloat horizontalOffset = proposedContentOffset.x + 5;
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray *array = [super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes *layoutAttributes in array) {
CGFloat itemOffset = layoutAttributes.frame.origin.x;
if (ABS(itemOffset - horizontalOffset) < ABS(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset;
}
}
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
This ensures that the scrolling ends with a margin of 5.0 on the left hand edge.
That's all I needed to do. I didn't need to set the flow layout in code at all.
Dan's solution is flawed. It does not handle user flicking well. The cases when user flicks fast and scroll did not move so much, have animation glitches.
My proposed alternative implementation has the same pagination as proposed before, but handles user flicking between pages.
#pragma mark - Pagination
- (CGFloat)pageWidth {
return self.itemSize.width + self.minimumLineSpacing;
}
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGFloat rawPageValue = self.collectionView.contentOffset.x / self.pageWidth;
CGFloat currentPage = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue);
CGFloat nextPage = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue);
BOOL pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5;
BOOL flicked = fabs(velocity.x) > [self flickVelocity];
if (pannedLessThanAPage && flicked) {
proposedContentOffset.x = nextPage * self.pageWidth;
} else {
proposedContentOffset.x = round(rawPageValue) * self.pageWidth;
}
return proposedContentOffset;
}
- (CGFloat)flickVelocity {
return 0.3;
}
Swift version of the accepted answer.
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalOffset = proposedContentOffset.x
let targetRect = CGRect(origin: CGPoint(x: proposedContentOffset.x, y: 0), size: self.collectionView!.bounds.size)
for layoutAttributes in super.layoutAttributesForElements(in: targetRect)! {
let itemOffset = layoutAttributes.frame.origin.x
if (abs(itemOffset - horizontalOffset) < abs(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
Valid for Swift 5.
Here's my implementation in Swift 5 for vertical cell-based paging:
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else {
let latestOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
return latestOffset
}
// Page height used for estimating and calculating paging.
let pageHeight = self.itemSize.height + self.minimumLineSpacing
// Make an estimation of the current page position.
let approximatePage = collectionView.contentOffset.y/pageHeight
// Determine the current page based on velocity.
let currentPage = velocity.y == 0 ? round(approximatePage) : (velocity.y < 0.0 ? floor(approximatePage) : ceil(approximatePage))
// Create custom flickVelocity.
let flickVelocity = velocity.y * 0.3
// Check how many pages the user flicked, if <= 1 then flickedPages should return 0.
let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity)
let newVerticalOffset = ((currentPage + flickedPages) * pageHeight) - collectionView.contentInset.top
return CGPoint(x: proposedContentOffset.x, y: newVerticalOffset)
}
Some notes:
Doesn't glitch
SET PAGING TO FALSE! (otherwise this won't work)
Allows you to set your own flickvelocity easily.
If something is still not working after trying this, check if your itemSize actually matches the size of the item as that's often a problem, especially when using collectionView(_:layout:sizeForItemAt:), use a custom variable with the itemSize instead.
This works best when you set self.collectionView.decelerationRate = UIScrollView.DecelerationRate.fast.
Here's a horizontal version (haven't tested it thoroughly so please forgive any mistakes):
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else {
let latestOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
return latestOffset
}
// Page width used for estimating and calculating paging.
let pageWidth = self.itemSize.width + self.minimumInteritemSpacing
// Make an estimation of the current page position.
let approximatePage = collectionView.contentOffset.x/pageWidth
// Determine the current page based on velocity.
let currentPage = velocity.x == 0 ? round(approximatePage) : (velocity.x < 0.0 ? floor(approximatePage) : ceil(approximatePage))
// Create custom flickVelocity.
let flickVelocity = velocity.x * 0.3
// Check how many pages the user flicked, if <= 1 then flickedPages should return 0.
let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity)
// Calculate newHorizontalOffset.
let newHorizontalOffset = ((currentPage + flickedPages) * pageWidth) - collectionView.contentInset.left
return CGPoint(x: newHorizontalOffset, y: proposedContentOffset.y)
}
This code is based on the code I use in my personal project, you can check it out here by downloading it and running the Example target.
For anyone looking for a solution that...
DOES NOT GLITCH when the user performs a short fast scroll (i.e. it considers positive and negative scroll velocities)
takes the collectionView.contentInset (and safeArea on iPhone X) into consideration
only considers thoes cells visible at the point of scrolling (for peformance)
uses well named variables and comments
is Swift 4
then please see below...
public class CarouselCollectionViewLayout: UICollectionViewFlowLayout {
override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else {
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
}
// Identify the layoutAttributes of cells in the vicinity of where the scroll view will come to rest
let targetRect = CGRect(origin: proposedContentOffset, size: collectionView.bounds.size)
let visibleCellsLayoutAttributes = layoutAttributesForElements(in: targetRect)
// Translate those cell layoutAttributes into potential (candidate) scrollView offsets
let candidateOffsets: [CGFloat]? = visibleCellsLayoutAttributes?.map({ cellLayoutAttributes in
if #available(iOS 11.0, *) {
return cellLayoutAttributes.frame.origin.x - collectionView.contentInset.left - collectionView.safeAreaInsets.left - sectionInset.left
} else {
return cellLayoutAttributes.frame.origin.x - collectionView.contentInset.left - sectionInset.left
}
})
// Now we need to work out which one of the candidate offsets is the best one
let bestCandidateOffset: CGFloat
if velocity.x > 0 {
// If the scroll velocity was POSITIVE, then only consider cells/offsets to the RIGHT of the proposedContentOffset.x
// Of the cells/offsets to the right, the NEAREST is the `bestCandidate`
// If there is no nearestCandidateOffsetToLeft then we default to the RIGHT-MOST (last) of ALL the candidate cells/offsets
// (this handles the scenario where the user has scrolled beyond the last cell)
let candidateOffsetsToRight = candidateOffsets?.toRight(ofProposedOffset: proposedContentOffset.x)
let nearestCandidateOffsetToRight = candidateOffsetsToRight?.nearest(toProposedOffset: proposedContentOffset.x)
bestCandidateOffset = nearestCandidateOffsetToRight ?? candidateOffsets?.last ?? proposedContentOffset.x
}
else if velocity.x < 0 {
// If the scroll velocity was NEGATIVE, then only consider cells/offsets to the LEFT of the proposedContentOffset.x
// Of the cells/offsets to the left, the NEAREST is the `bestCandidate`
// If there is no nearestCandidateOffsetToLeft then we default to the LEFT-MOST (first) of ALL the candidate cells/offsets
// (this handles the scenario where the user has scrolled beyond the first cell)
let candidateOffsetsToLeft = candidateOffsets?.toLeft(ofProposedOffset: proposedContentOffset.x)
let nearestCandidateOffsetToLeft = candidateOffsetsToLeft?.nearest(toProposedOffset: proposedContentOffset.x)
bestCandidateOffset = nearestCandidateOffsetToLeft ?? candidateOffsets?.first ?? proposedContentOffset.x
}
else {
// If the scroll velocity was ZERO we consider all `candidate` cells (regarless of whether they are to the left OR right of the proposedContentOffset.x)
// The cell/offset that is the NEAREST is the `bestCandidate`
let nearestCandidateOffset = candidateOffsets?.nearest(toProposedOffset: proposedContentOffset.x)
bestCandidateOffset = nearestCandidateOffset ?? proposedContentOffset.x
}
return CGPoint(x: bestCandidateOffset, y: proposedContentOffset.y)
}
}
fileprivate extension Sequence where Iterator.Element == CGFloat {
func toLeft(ofProposedOffset proposedOffset: CGFloat) -> [CGFloat] {
return filter() { candidateOffset in
return candidateOffset < proposedOffset
}
}
func toRight(ofProposedOffset proposedOffset: CGFloat) -> [CGFloat] {
return filter() { candidateOffset in
return candidateOffset > proposedOffset
}
}
func nearest(toProposedOffset proposedOffset: CGFloat) -> CGFloat? {
guard let firstCandidateOffset = first(where: { _ in true }) else {
// If there are no elements in the Sequence, return nil
return nil
}
return reduce(firstCandidateOffset) { (bestCandidateOffset: CGFloat, candidateOffset: CGFloat) -> CGFloat in
let candidateOffsetDistanceFromProposed = fabs(candidateOffset - proposedOffset)
let bestCandidateOffsetDistancFromProposed = fabs(bestCandidateOffset - proposedOffset)
if candidateOffsetDistanceFromProposed < bestCandidateOffsetDistancFromProposed {
return candidateOffset
}
return bestCandidateOffset
}
}
}
While this answer has been a great help to me, there is a noticeable flicker when you swipe fast on a small distance. It's much easier to reproduce it on the device.
I found that this always happens when collectionView.contentOffset.x - proposedContentOffset.x and velocity.x have different sings.
My solution was to ensure that proposedContentOffset is more than contentOffset.x if velocity is positive, and less if it is negative. It's in C# but should be fairly simple to translate to Objective C:
public override PointF TargetContentOffset (PointF proposedContentOffset, PointF scrollingVelocity)
{
/* Determine closest edge */
float offSetAdjustment = float.MaxValue;
float horizontalCenter = (float) (proposedContentOffset.X + (this.CollectionView.Bounds.Size.Width / 2.0));
RectangleF targetRect = new RectangleF (proposedContentOffset.X, 0.0f, this.CollectionView.Bounds.Size.Width, this.CollectionView.Bounds.Size.Height);
var array = base.LayoutAttributesForElementsInRect (targetRect);
foreach (var layoutAttributes in array) {
float itemHorizontalCenter = layoutAttributes.Center.X;
if (Math.Abs (itemHorizontalCenter - horizontalCenter) < Math.Abs (offSetAdjustment)) {
offSetAdjustment = itemHorizontalCenter - horizontalCenter;
}
}
float nextOffset = proposedContentOffset.X + offSetAdjustment;
/*
* ... unless we end up having positive speed
* while moving left or negative speed while moving right.
* This will cause flicker so we resort to finding next page
* in the direction of velocity and use it.
*/
do {
proposedContentOffset.X = nextOffset;
float deltaX = proposedContentOffset.X - CollectionView.ContentOffset.X;
float velX = scrollingVelocity.X;
// If their signs are same, or if either is zero, go ahead
if (Math.Sign (deltaX) * Math.Sign (velX) != -1)
break;
// Otherwise, look for the closest page in the right direction
nextOffset += Math.Sign (scrollingVelocity.X) * SnapStep;
} while (IsValidOffset (nextOffset));
return proposedContentOffset;
}
bool IsValidOffset (float offset)
{
return (offset >= MinContentOffset && offset <= MaxContentOffset);
}
This code is using MinContentOffset, MaxContentOffset and SnapStep which should be trivial for you to define. In my case they turned out to be
float MinContentOffset {
get { return -CollectionView.ContentInset.Left; }
}
float MaxContentOffset {
get { return MinContentOffset + CollectionView.ContentSize.Width - ItemSize.Width; }
}
float SnapStep {
get { return ItemSize.Width + MinimumLineSpacing; }
}
After long testing I found solution to snap to center with custom cell width (each cell has diff. width) which fixes the flickering. Feel free to improve the script.
- (CGPoint) targetContentOffsetForProposedContentOffset: (CGPoint) proposedContentOffset withScrollingVelocity: (CGPoint)velocity
{
CGFloat offSetAdjustment = MAXFLOAT;
CGFloat horizontalCenter = (CGFloat) (proposedContentOffset.x + (self.collectionView.bounds.size.width / 2.0));
//setting fastPaging property to NO allows to stop at page on screen (I have pages lees, than self.collectionView.bounds.size.width)
CGRect targetRect = CGRectMake(self.fastPaging ? proposedContentOffset.x : self.collectionView.contentOffset.x,
0.0,
self.collectionView.bounds.size.width,
self.collectionView.bounds.size.height);
NSArray *attributes = [self layoutAttributesForElementsInRect:targetRect];
NSPredicate *cellAttributesPredicate = [NSPredicate predicateWithBlock: ^BOOL(UICollectionViewLayoutAttributes * _Nonnull evaluatedObject,
NSDictionary<NSString *,id> * _Nullable bindings)
{
return (evaluatedObject.representedElementCategory == UICollectionElementCategoryCell);
}];
NSArray *cellAttributes = [attributes filteredArrayUsingPredicate: cellAttributesPredicate];
UICollectionViewLayoutAttributes *currentAttributes;
for (UICollectionViewLayoutAttributes *layoutAttributes in cellAttributes)
{
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offSetAdjustment))
{
currentAttributes = layoutAttributes;
offSetAdjustment = itemHorizontalCenter - horizontalCenter;
}
}
CGFloat nextOffset = proposedContentOffset.x + offSetAdjustment;
proposedContentOffset.x = nextOffset;
CGFloat deltaX = proposedContentOffset.x - self.collectionView.contentOffset.x;
CGFloat velX = velocity.x;
// detection form gist.github.com/rkeniger/7687301
// based on http://stackoverflow.com/a/14291208/740949
if (fabs(deltaX) <= FLT_EPSILON || fabs(velX) <= FLT_EPSILON || (velX > 0.0 && deltaX > 0.0) || (velX < 0.0 && deltaX < 0.0))
{
}
else if (velocity.x > 0.0)
{
// revert the array to get the cells from the right side, fixes not correct center on different size in some usecases
NSArray *revertedArray = [[array reverseObjectEnumerator] allObjects];
BOOL found = YES;
float proposedX = 0.0;
for (UICollectionViewLayoutAttributes *layoutAttributes in revertedArray)
{
if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell)
{
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
if (itemHorizontalCenter > proposedContentOffset.x) {
found = YES;
proposedX = nextOffset + (currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2);
} else {
break;
}
}
}
// dont set on unfound element
if (found) {
proposedContentOffset.x = proposedX;
}
}
else if (velocity.x < 0.0)
{
for (UICollectionViewLayoutAttributes *layoutAttributes in cellAttributes)
{
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
if (itemHorizontalCenter > proposedContentOffset.x)
{
proposedContentOffset.x = nextOffset - ((currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2));
break;
}
}
}
proposedContentOffset.y = 0.0;
return proposedContentOffset;
}
refer to this answer by Dan Abramov here's Swift version
override func targetContentOffset(
forProposedContentOffset proposedContentOffset: CGPoint,
withScrollingVelocity velocity: CGPoint
) -> CGPoint {
var _proposedContentOffset = CGPoint(
x: proposedContentOffset.x, y: proposedContentOffset.y
)
var offSetAdjustment: CGFloat = CGFloat.greatestFiniteMagnitude
let horizontalCenter: CGFloat = CGFloat(
proposedContentOffset.x + (self.collectionView!.bounds.size.width / 2.0)
)
let targetRect = CGRect(
x: proposedContentOffset.x,
y: 0.0,
width: self.collectionView!.bounds.size.width,
height: self.collectionView!.bounds.size.height
)
let array: [UICollectionViewLayoutAttributes] =
self.layoutAttributesForElements(in: targetRect)!
as [UICollectionViewLayoutAttributes]
for layoutAttributes: UICollectionViewLayoutAttributes in array {
if layoutAttributes.representedElementCategory == UICollectionView.ElementCategory.cell {
let itemHorizontalCenter: CGFloat = layoutAttributes.center.x
if abs(itemHorizontalCenter - horizontalCenter) < abs(offSetAdjustment) {
offSetAdjustment = itemHorizontalCenter - horizontalCenter
}
}
}
var nextOffset: CGFloat = proposedContentOffset.x + offSetAdjustment
repeat {
_proposedContentOffset.x = nextOffset
let deltaX = proposedContentOffset.x - self.collectionView!.contentOffset.x
let velX = velocity.x
if
deltaX == 0.0 || velX == 0 || (velX > 0.0 && deltaX > 0.0) ||
(velX < 0.0 && deltaX < 0.0)
{
break
}
if velocity.x > 0.0 {
nextOffset = nextOffset + self.snapStep()
} else if velocity.x < 0.0 {
nextOffset = nextOffset - self.snapStep()
}
} while self.isValidOffset(offset: nextOffset)
_proposedContentOffset.y = 0.0
return _proposedContentOffset
}
func isValidOffset(offset: CGFloat) -> Bool {
return (offset >= CGFloat(self.minContentOffset()) &&
offset <= CGFloat(self.maxContentOffset()))
}
func minContentOffset() -> CGFloat {
return -CGFloat(self.collectionView!.contentInset.left)
}
func maxContentOffset() -> CGFloat {
return CGFloat(
self.minContentOffset() + self.collectionView!.contentSize.width - self.itemSize.width
)
}
func snapStep() -> CGFloat {
return self.itemSize.width + self.minimumLineSpacing
}
or gist here https://gist.github.com/katopz/8b04c783387f0c345cd9
Here is my Swift solution on a horizontally scrolling collection view. It's simple, sweet and avoids any flickering.
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return proposedContentOffset }
let currentXOffset = collectionView.contentOffset.x
let nextXOffset = proposedContentOffset.x
let maxIndex = ceil(currentXOffset / pageWidth())
let minIndex = floor(currentXOffset / pageWidth())
var index: CGFloat = 0
if nextXOffset > currentXOffset {
index = maxIndex
} else {
index = minIndex
}
let xOffset = pageWidth() * index
let point = CGPointMake(xOffset, 0)
return point
}
func pageWidth() -> CGFloat {
return itemSize.width + minimumInteritemSpacing
}
a small issue I encountered while using targetContentOffsetForProposedContentOffset is a problem with the last cell not adjusting according to the new point I returned.
I found out that the CGPoint I returned had a Y value bigger then allowed so i used the following code at the end of my targetContentOffsetForProposedContentOffset implementation:
// if the calculated y is bigger then the maximum possible y we adjust accordingly
CGFloat contentHeight = self.collectionViewContentSize.height;
CGFloat collectionViewHeight = self.collectionView.bounds.size.height;
CGFloat maxY = contentHeight - collectionViewHeight;
if (newY > maxY)
{
newY = maxY;
}
return CGPointMake(0, newY);
just to make it clearer this is my full layout implementation which just imitates vertical paging behavior:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
return [self targetContentOffsetForProposedContentOffset:proposedContentOffset];
}
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
{
CGFloat heightOfPage = self.itemSize.height;
CGFloat heightOfSpacing = self.minimumLineSpacing;
CGFloat numOfPage = lround(proposedContentOffset.y / (heightOfPage + heightOfSpacing));
CGFloat newY = numOfPage * (heightOfPage + heightOfSpacing);
// if the calculated y is bigger then the maximum possible y we adjust accordingly
CGFloat contentHeight = self.collectionViewContentSize.height;
CGFloat collectionViewHeight = self.collectionView.bounds.size.height;
CGFloat maxY = contentHeight - collectionViewHeight;
if (newY > maxY)
{
newY = maxY;
}
return CGPointMake(0, newY);
}
hopefully this will save someone some time and a headache
I prefer to allow user flicking through several pages. So here is my version of targetContentOffsetForProposedContentOffset (which based on DarthMike answer) for vertical layout.
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
CGFloat approximatePage = self.collectionView.contentOffset.y / self.pageHeight;
CGFloat currentPage = (velocity.y < 0.0) ? floor(approximatePage) : ceil(approximatePage);
NSInteger flickedPages = ceil(velocity.y / self.flickVelocity);
if (flickedPages) {
proposedContentOffset.y = (currentPage + flickedPages) * self.pageHeight;
} else {
proposedContentOffset.y = currentPage * self.pageHeight;
}
return proposedContentOffset;
}
- (CGFloat)pageHeight {
return self.itemSize.height + self.minimumLineSpacing;
}
- (CGFloat)flickVelocity {
return 1.2;
}
Fogmeisters answer worked for me unless I scrolled to the end of the row. My cells don't fit neatly on the screen so it would scroll to the end and jump back with a jerk so that the last cell always overlapped the right edge of the screen.
To prevent this add the following line of code at the start of the targetcontentoffset method
if(proposedContentOffset.x>self.collectionViewContentSize.width-320-self.sectionInset.right)
return proposedContentOffset;
#André Abreu's Code
Swift3 version
class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalOffset = proposedContentOffset.x
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: self.collectionView!.bounds.size.width, height: self.collectionView!.bounds.size.height)
for layoutAttributes in super.layoutAttributesForElements(in: targetRect)! {
let itemOffset = layoutAttributes.frame.origin.x
if abs(itemOffset - horizontalOffset) < abs(offsetAdjustment){
offsetAdjustment = itemOffset - horizontalOffset
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
Swift 4
The easiest solution for collection view with cells of one size (horizontal scroll):
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return proposedContentOffset }
// Calculate width of your page
let pageWidth = calculatedPageWidth()
// Calculate proposed page
let proposedPage = round(proposedContentOffset.x / pageWidth)
// Adjust necessary offset
let xOffset = pageWidth * proposedPage - collectionView.contentInset.left
return CGPoint(x: xOffset, y: 0)
}
func calculatedPageWidth() -> CGFloat {
return itemSize.width + minimumInteritemSpacing
}
A shorter solution (assuming you're caching your layout attributes):
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
let proposedEndFrame = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView!.bounds.width, height: collectionView!.bounds.height)
let targetLayoutAttributes = cache.max { $0.frame.intersection(proposedEndFrame).width < $1.frame.intersection(proposedEndFrame).width }!
return CGPoint(x: targetLayoutAttributes.frame.minX - horizontalPadding, y: 0)
}
To put this in context:
class Layout : UICollectionViewLayout {
private var cache: [UICollectionViewLayoutAttributes] = []
private static let horizontalPadding: CGFloat = 16
private static let interItemSpacing: CGFloat = 8
override func prepare() {
let (itemWidth, itemHeight) = (collectionView!.bounds.width - 2 * Layout.horizontalPadding, collectionView!.bounds.height)
cache.removeAll()
let count = collectionView!.numberOfItems(inSection: 0)
var x: CGFloat = Layout.horizontalPadding
for item in (0..<count) {
let indexPath = IndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: x, y: 0, width: itemWidth, height: itemHeight)
cache.append(attributes)
x += itemWidth + Layout.interItemSpacing
}
}
override var collectionViewContentSize: CGSize {
let width: CGFloat
if let maxX = cache.last?.frame.maxX {
width = maxX + Layout.horizontalPadding
} else {
width = collectionView!.width
}
return CGSize(width: width, height: collectionView!.height)
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache.first { $0.indexPath == indexPath }
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return cache.filter { $0.frame.intersects(rect) }
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
let proposedEndFrame = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView!.bounds.width, height: collectionView!.bounds.height)
let targetLayoutAttributes = cache.max { $0.frame.intersection(proposedEndFrame).width < $1.frame.intersection(proposedEndFrame).width }!
return CGPoint(x: targetLayoutAttributes.frame.minX - Layout.horizontalPadding, y: 0)
}
}
To make sure it works in Swift version (swift 5 now), I used the answer from #André Abreu, I add some more informations:
When subclassing UICollectionViewFlowLayout, the "override func awakeFromNib(){}" doesn't works (don't know why). Instead, I used "override init(){super.init()}"
This is my code put in class SubclassFlowLayout: UICollectionViewFlowLayout {} :
let padding: CGFloat = 16
override init() {
super.init()
self.minimumLineSpacing = padding
self.minimumInteritemSpacing = 2
self.scrollDirection = .horizontal
self.sectionInset = UIEdgeInsets(top: 0, left: padding, bottom: 0, right: 100) //right = "should set for footer" (Horizental)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let leftInset = padding
let horizontalOffset = proposedContentOffset.x + leftInset // leftInset is for "where you want the item stop on the left"
let targetRect = CGRect(origin: CGPoint(x: proposedContentOffset.x, y: 0), size: self.collectionView!.bounds.size)
for layoutAttributes in super.layoutAttributesForElements(in: targetRect)! {
let itemOffset = layoutAttributes.frame.origin.x
if (abs(itemOffset - horizontalOffset) < abs(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset
}
}
let targetPoint = CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
return targetPoint
}
After subclassing, make sure to put this in ViewDidLoad():
customCollectionView.collectionViewLayout = SubclassFlowLayout()
customCollectionView.isPagingEnabled = false
customCollectionView.decelerationRate = .fast //-> this for scrollView speed
For those looking for a solution in Swift:
class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
private let collectionViewHeight: CGFloat = 200.0
private let screenWidth: CGFloat = UIScreen.mainScreen().bounds.width
override func awakeFromNib() {
super.awakeFromNib()
self.itemSize = CGSize(width: [InsertItemWidthHere], height: [InsertItemHeightHere])
self.minimumInteritemSpacing = [InsertItemSpacingHere]
self.scrollDirection = .Horizontal
let inset = (self.screenWidth - CGFloat(self.itemSize.width)) / 2
self.collectionView?.contentInset = UIEdgeInsets(top: 0,
left: inset,
bottom: 0,
right: inset)
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offsetAdjustment = CGFloat.max
let horizontalOffset = proposedContentOffset.x + ((self.screenWidth - self.itemSize.width) / 2)
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: self.screenWidth, height: self.collectionViewHeight)
var array = super.layoutAttributesForElementsInRect(targetRect)
for layoutAttributes in array! {
let itemOffset = layoutAttributes.frame.origin.x
if (abs(itemOffset - horizontalOffset) < abs(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
It is not about collectionView, but it works better.
It is the best solution I ever seen.
Just use it with .linear type.
https://github.com/nicklockwood/iCarousel
God bless the author!:)
Here is a demo for paging by cell (when scroll fast, not skip one or more cell): https://github.com/ApesTalk/ATPagingByCell

How to run the bubble(on slider top) with the slidervalue and the position same as thumb of slider?

I have a slider with the minValue = 0 and maximumValue = 1000. I have a bubble on slider which runs with the thumb of the slider and displays the value of the slider.
But i am unable to run the bubble with the slider thumb.
Here's the code snippet:
CGFloat sliderMax = localSlider.maximumValue;
CGFloat sliderMin = localSlider.minimumValue;
CGFloat sliderMaxMinDiff = sliderMax - sliderMin;
CGFloat sliderValue = _dsp;
CGFloat halfMax = (sliderMax+sliderMin)/2.0;
//int hMax = [halfMax intValue];
CGFloat xCoord = halfMax- 55.0;
CGFloat yCoord = (CGFloat)_positionX;
if (sliderValue > halfMax)
{
xCoord = xCoord-(sliderValue-halfMax);
}
else
{
xCoord = xCoord + (halfMax-sliderValue);
}
xCoord= xCoord + (642/sliderMaxMinDiff)*(sliderValue-sliderMin);
newB.frame = CGRectMake(xCoord,yCoord,84,47);
#Ashutosh It might be of some use
-(void)sliderValueChanged:(id)sender{
UISlider *slider = (UISlider*)sender;
CGFloat sliderMin = slider.minimumValue;
CGFloat sliderMax = slider.maximumValue;
CGFloat sliderMaxMinDiff = sliderMax - sliderMin;
CGFloat sliderValue = slider.value;
if(sliderMin < 0.0) {
sliderValue = slider.value-sliderMin;
sliderMax = sliderMax - sliderMin;
sliderMin = 0.0;
sliderMaxMinDiff = sliderMax - sliderMin;
}
CGFloat xCoord = ((sliderValue-sliderMin)/sliderMaxMinDiff)*[slider frame].size.width-SLIDER_CALLOUT_WIDTH/2.0;
CGFloat halfMax = (sliderMax+sliderMin)/2.0;
if(sliderValue > halfMax) {
sliderValue = (sliderValue - halfMax)+(sliderMin*1.0);
sliderValue = sliderValue/halfMax;
sliderValue = sliderValue*11.0;
xCoord = xCoord - sliderValue;
}
else if(sliderValue < halfMax) {
sliderValue = (halfMax - sliderValue)+(sliderMin*1.0);
sliderValue = sliderValue/halfMax;
sliderValue = sliderValue*11.0;
xCoord = xCoord + sliderValue;
}
int index = ceil(slider.value) ;
if (MIN_INDEX<= index <=MAX_INDEX) {
CGPoint callOutPoint = CGPointMake(xCoord, slider.frame.origin.y);
//[self drawCallOutAtRect:callOutPoint andDate:[self.dataSourceArray objectAtIndex:(8-index)]];
//Call A Function To draw Bubble on Slider Top
}
previousIndex = index;
}
You can also take some hint from https://github.com/elc/ELCSlider
Here is a screen shot of what i made
I added the slider using these values-
UISlider *timeSliderObj = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 280, 44)];
timeSliderObj.maximumValue = 8;
timeSliderObj.minimumValue = 1;
timeSliderObj.value = 8;

Finding closest object to CGPoint

I have four UIViews on a UIScrollView (screen divided into quartiles)
On the quartiles, I have a few objects (UIImageViews), on each quartile.
When the user taps the screen, I want to find the closest object to the given CGPoint?
Any ideas?
I have the CGPoint and frame (CGRect) of the objects within each quartile.
UPDATE:
(source: skitch.com)Red Pins are UIImageViews.
// UIScrollView
NSLog(#" UIScrollView: %#", self);
// Here's the tap on the Window in UIScrollView's coordinates
NSLog(#"TapPoint: %3.2f, %3.2f", tapLocation.x, tapLocation.y);
// Find Distance between tap and objects
NSArray *arrayOfCGRrectObjects = [self subviews];
NSEnumerator *enumerator = [arrayOfCGRrectObjects objectEnumerator];
for (UIView *tilesOnScrollView in enumerator) {
// each tile may have 0 or more images
for ( UIView *subview in tilesOnScrollView.subviews ) {
// Is this an UIImageView?
if ( [NSStringFromClass([subview class]) isEqualToString:#"UIImageView"]) {
// Yes, here are the UIImageView details (subView)
NSLog(#"%#", subview);
// Convert CGPoint of UIImageView to CGPoint of UIScrollView for comparison...
// First, Convert CGPoint from UIScrollView to UIImageView's coordinate system for reference
CGPoint found = [subview convertPoint:tapLocation fromView:self];
NSLog(#"Converted Point from ScrollView: %3.2f, %3.2f", found.x, found.y);
// Second, Convert CGPoint from UIScrollView to Window's coordinate system for reference
found = [subview convertPoint:subview.frame.origin toView:nil];
NSLog(#"Converted Point in Window: %3.2f, %3.2f", found.x, found.y);
// Finally, use the object's CGPoint in UIScrollView's coordinates for comparison
found = [subview convertPoint:subview.frame.origin toView:self]; // self is UIScrollView (see above)
NSLog(#"Converted Point: %3.2f, %3.2f", found.x, found.y);
// Determine tap CGPoint in UIImageView's coordinate system
CGPoint localPoint = [touch locationInView:subview];
NSLog(#"LocateInView: %3.2f, %3.2f",localPoint.x, localPoint.y );
//Kalle's code
CGRect newRect = CGRectMake(found.x, found.y, 32, 39);
NSLog(#"Kalle's Distance: %3.2f",[self distanceBetweenRect:newRect andPoint:tapLocation]);
}
Debug Console
Here's the problem. Each Tile is 256x256. The first UIImageView's CGPoint converted to the
UIScrollView's coordinate system (53.25, 399.36) should be dead on with the tapPoint (30,331). Why the difference?? The other point to the right of the tapped point is calculating closer (distance wise)??
<CALayer: 0x706a690>>
[207] TapPoint: 30.00, 331.00
[207] <UIImageView: 0x7073db0; frame = (26.624 71.68; 32 39); opaque = NO; userInteractionEnabled = NO; tag = 55; layer = <CALayer: 0x70747d0>>
[207] Converted Point from ScrollView: 3.38, 3.32
[207] Converted Point in Window: 53.25, 463.36
[207] Converted Point: 53.25, 399.36 *** Looks way off!
[207] LocateInView: 3.38, 3.32
[207] Kalle's Distance: 72.20 **** THIS IS THE TAPPED POINT
[207] <UIImageView: 0x7074fb0; frame = (41.984 43.008; 32 39); opaque = NO; userInteractionEnabled = NO; tag = 55; layer = <CALayer: 0x7074fe0>>
[207] Converted Point from ScrollView: -11.98, 31.99
[207] Converted Point in Window: 83.97, 406.02
[207] Converted Point: 83.97, 342.02
[207] LocateInView: -11.98, 31.99
207] Kalle's Distance: 55.08 ***** BUT THIS ONE's CLOSER??????
The following method should do the trick. If you spot anything weird in it feel free to point it out.
- (CGFloat)distanceBetweenRect:(CGRect)rect andPoint:(CGPoint)point
{
// first of all, we check if point is inside rect. If it is, distance is zero
if (CGRectContainsPoint(rect, point)) return 0.f;
// next we see which point in rect is closest to point
CGPoint closest = rect.origin;
if (rect.origin.x + rect.size.width < point.x)
closest.x += rect.size.width; // point is far right of us
else if (point.x > rect.origin.x)
closest.x = point.x; // point above or below us
if (rect.origin.y + rect.size.height < point.y)
closest.y += rect.size.height; // point is far below us
else if (point.y > rect.origin.y)
closest.y = point.y; // point is straight left or right
// we've got a closest point; now pythagorean theorem
// distance^2 = [closest.x,y - closest.x,point.y]^2 + [closest.x,point.y - point.x,y]^2
// i.e. [closest.y-point.y]^2 + [closest.x-point.x]^2
CGFloat a = powf(closest.y-point.y, 2.f);
CGFloat b = powf(closest.x-point.x, 2.f);
return sqrtf(a + b);
}
Example output:
CGPoint p = CGPointMake(12,12);
CGRect a = CGRectMake(5,5,10,10);
CGRect b = CGRectMake(13,11,10,10);
CGRect c = CGRectMake(50,1,10,10);
NSLog(#"distance p->a: %f", [self distanceBetweenRect:a andPoint:p]);
// 2010-08-24 13:36:39.506 app[4388:207] distance p->a: 0.000000
NSLog(#"distance p->b: %f", [self distanceBetweenRect:b andPoint:p]);
// 2010-08-24 13:38:03.149 app[4388:207] distance p->b: 1.000000
NSLog(#"distance p->c: %f", [self distanceBetweenRect:c andPoint:p]);
// 2010-08-24 13:39:52.148 app[4388:207] distance p->c: 38.013157
There might be more optimized versions out there, so might be worth digging more.
The following method determines the distance between two CGPoints.
- (CGFloat)distanceBetweenPoint:(CGPoint)a andPoint:(CGPoint)b
{
CGFloat a2 = powf(a.x-b.x, 2.f);
CGFloat b2 = powf(a.y-b.y, 2.f);
return sqrtf(a2 + b2)
}
Update: removed fabsf(); -x^2 is the same as x^2, so it's unnecessary.
Update 2: added distanceBetweenPoint:andPoint: method too, for completeness.
If you're using Swift, here's how you can calculate the distance between a CGPoint and a CGRect (e.g. an UIView's frame)
private func distanceToRect(rect: CGRect, fromPoint point: CGPoint) -> CGFloat {
// if it's on the left then (rect.minX - point.x) > 0 and (point.x - rect.maxX) < 0
// if it's on the right then (rect.minX - point.x) < 0 and (point.x - rect.maxX) > 0
// if it's inside the rect then both of them < 0.
let dx = max(rect.minX - point.x, point.x - rect.maxX, 0)
// same as dx
let dy = max(rect.minY - point.y, point.y - rect.maxY, 0)
// if one of them == 0 then the distance is the other one.
if dx * dy == 0 {
return max(dx, dy)
} else {
// both are > 0 then the distance is the hypotenuse
return hypot(dx, dy)
}
}
Thanks #cristian,
Here's Objective-C version of your answer
- (CGFloat)distanceToRect:(CGRect)rect fromPoint:(CGPoint)point
{
CGFloat dx = MAX(0, MAX(CGRectGetMinX(rect) - point.x, point.x - CGRectGetMaxX(rect)));
CGFloat dy = MAX(0, MAX(CGRectGetMinY(rect) - point.y, point.y - CGRectGetMaxY(rect)));
if (dx * dy == 0)
{
return MAX(dx, dy);
}
else
{
return hypot(dx, dy);
}
}
Shorter #cristian answer:
func distance(from rect: CGRect, to point: CGPoint) -> CGFloat {
let dx = max(rect.minX - point.x, point.x - rect.maxX, 0)
let dy = max(rect.minY - point.y, point.y - rect.maxY, 0)
return dx * dy == 0 ? max(dx, dy) : hypot(dx, dy)
}
Personally, I would implement this as a CGPoint extension:
extension CGPoint {
func distance(from rect: CGRect) -> CGFloat {
let dx = max(rect.minX - x, x - rect.maxX, 0)
let dy = max(rect.minY - y, y - rect.maxY, 0)
return dx * dy == 0 ? max(dx, dy) : hypot(dx, dy)
}
}
Alternatively, you can also implement it as a CGRect extension:
extension CGRect {
func distance(from point: CGPoint) -> CGFloat {
let dx = max(minX - point.x, point.x - maxX, 0)
let dy = max(minY - point.y, point.y - maxY, 0)
return dx * dy == 0 ? max(dx, dy) : hypot(dx, dy)
}
}