CATransform3D - understanding the transform values - ios

The picture shows a simple UIView after applying the following transform:
- (CATransform3D) transformForOpenedMenu
{
CATransform3D transform = CATransform3DIdentity;
transform.m34 = -1.0 /450;
transform = CATransform3DRotate(transform, D2R(40), 0, 1, 0);
transform = CATransform3DTranslate(transform, 210, 150, -500);
return transform;
}
I'm trying to make the distances highlighted with black to have equal length. Could you please help me understand the logic behind the values and calculations?
Cheers
UPD Sept 13
Looks like removing 3DTranslate keeps distances equal. I see I can use layer's frame property to reposition rotated view to the bottom left of the screen. Not yet sure, but this might actually work.

The .m34 value you are setting is best set on the sublayerTransform of the containing view rather than the view you are transforming.
I don't fully understand the maths behind affine transforms so I made this project which allows me to play around with the transform values to achieve the effect I want. You can plug in the values from your code above and see what it looks like, though note that there is already a perspective value applied using the sublayerTransform property mentioned above.
For your specific case, I think you want to adjust the anchor point of the layer to (0.0,0.5) and apply the rotation transform only. This assumes you want the menu to swing back like a door, with the hinges on the left edge.

The problem you're seeing is caused by your CATransform3DTranslate call. You're essentially setting the Y Axis off center, and hence seeing a different perspective view of the frame.
Think of it this way;
You're standing in the center of a long narrow field stretching off into the horizon. The edge of the field appears as if it is converges to a center point somewhere off in the distance. The angle of each edge to the converging point will appear equal if you are at the center of the field. If, on the other hand, you move either to the left or the right, the angles change and one will seem greater than the other (inversely opposite of course).
This is essentially what is happening with your view; As your converging points are to the right, changing the Y axis away from 0 will have the same effect as moving to the left or right in my example above. You're no longer looking at the parallel lines from the center.
so in your code above Setting the ty in CATransform3DTranslate to 0 Should fix your problem I.E.
transform = CATransform3DTranslate(transform, 210, 0, -500);
You may also need to alter the tz and tx Value to make it fit.

OK, so what eventually solved my question is this:
3D transform on Y axis to swing the view like a door transform = CATransform3DRotate(transform, D2R(40), 0, 1, 0);
set Z anchor point on a layer, to move it back targetView.layer.anchorPointZ = 850;
adjust layer position so that the view is located slightly to the bottom left of the parent view:
newPosition.x += 135 * positionDirection;
newPosition.y += 70 * positionDirection;
This sequence adjusts position without CATransform3DTranslate and keeps the 'swinged' effect not distorted.
Thanks everybody!

Related

How to reset a Rectangle's x,y,width,height, after transform

I have an app that uses konvajs, where I set rectangles to be resizable. I have it set such that after I transform the rectangle I set the scaleX and scaleY to 1 so I can just use x, y, width, and height. I do this with the following code:
myRectangle.on('transformend', function() {
myRectangle.width(Math.round(myRectangle.width() * myRectangle.scaleX()));
myRectangle.height(Math.round(myRectangle.height() * myRectangle.scaleY()));
myRectangle.scaleX(1);
myRectangle.scaleY(1);
});
However, sometimes after I resize (usually if I "flip" the rectangle by dragging up or to the left), the x, y, width and height are strange values. Sometimes the width or height is negative, sometimes it seems like the x and y positions do not refer to the top left of the rectangle. I want to be able to extract information about the rectangle, so I would like position to be top left of the rectangle with positive width and height values. I don't mind resetting these values after the rectangle is tranformed, but I am not quite sure how konvajs is calculating the x,y,width, and height so I can't properly reset them. Is there some metric indicating when a tranform "flips" a rectangle? Or some other way to reset it?
It seems that setting flipEnabled and rotationEnabled to false on the transformer prevents rotations from happening.
To get a visual sense of what is happening to the attrs during the transform, take a look at the demo in the official docs here and pay special attention to width/height, rotation and scale as you resize by dragging the right edge first, then repeat with the bottom edge.
It will help to understand that dragging a Transformer handle changes the scale of the rectangle - not the width or height. However this is not the end of the story - if you 'flip' the shape in the horizontal axis then you will see that the rotation is changed from zero to 180 degrees and the scaleX remains positive. But if you drag and flip the shape in the vertical axis then there is no rotation effect and the scaleY switches to negative.
Long story short - at the moment I can't think of a useful use-case that requires trying to redraw the rectangle without scale or rotation affects, which I will refer to as the 'plain' rect versus the 'exotic' rect you get after using the Transformer.
If the use-case is hit detection via your own math then you have everything you need to know in the rects x & y, width & height, rotation and scaleX & scaleY. Even if you could get the attrs for a plain rect you would still have the same params to plug into your math, so recomputing the plain rect is wasted effort.
If the use-case is storage (serialization) of the rect's attrs then again the same point as above - you need to store the position, rotation, size, and scale so as to be able to redraw it later.
A legitimate use-case for resetting scale to 1 would be if your app's business case requires it. But this only covers resetting:
rect.seAttrs({
width: rect.width() * scaleX,
height: rect.height() * scaleY,
scaleX: 1,
scaleY: 1
}
and leaves the rect at the same position and rotation.
Conclusion: attempting to recompute a plain rect from an exotic rect may not be worth the effort in some cases.

CGAffineTransform not scaling origin correctly

I may be misunderstanding how the CGAffineTransform works but it seems to be giving strange results for the origin of the frame.
for example :
print(attribute.frame)
attribute.transform = CGAffineTransform(scaleX: 0.68, y: 0.68)
print(attribute.frame)
gives the results :
(213.0, 54.0, 459.0, 23.5)
(286.29948979591836, 57.75280612244898, 312.4010204081633, 15.994387755102032)
The width and height scale correctly but the x and y origin have increased in value.
The transform uses the center of your view as anchor point. The result being that the center stays the same, should be (442.5, 65,75) if i calculate correctly but the origin will move (increase in value if you scale down, and decrease if you scale up). There are various techniques to change the anchor point if you want to keep the origin, perhaps take a look at this thread : Scale with CGAffineTransform and set the anchor
I thinks the transform must be apply to the center of rect.
I don't know what is the type of attribute. Maybe there is something called anchor inside attribute. You can try to change the property.

Polar transformation in iOS

Can anyone help me to achieve this kind of animated transformation through Core Graphics. Look at the rough sketch:
This is a simple chart graphic, and I need to transform a histogramm-style bar (left shape) to a pie chart (right shape).
Literally the task is to roll a rectangle to a ring with a smooth animation. I almost found the way to do this with a tricky queue of drawings, mask clippings and affine transformations but this won't look exactly how I want it to look.
This is an interesting challenge, especially as you want to maintain the different segments. I won't give you a full answer (i.e full example code to achieving this), but I will explain what I think needs to be done to achieve the effect that you want.
Paths
First, I see both of these diagrams as a single line that is stroked (let's ignore the segments for a moment), so the challenge is going from a straight line to an enclosed circle.
I propose the following two paths, that you can animate between to achieve a nice wrapping effect.
// As we render a circle as a chain of straight line segments
// changing the count of said segments makes the circle more or less smooth
// Try this with other values, such as 8 or 32
let segments = 72
// With this segment count, the angle of each segment in the circle is
let angle = (2 * CGFloat(M_PI)) / CGFloat(segments)
// First path (straight)
let length = CGFloat(300.0)
let segmentLength = length / CGFloat(segments)
let straightPath = CGPathCreateMutable()
CGPathMoveToPoint(straightPath, nil, 0.0, 0.0)
for i in 0...segments {
CGPathAddLineToPoint(straightPath, nil, 0.0, CGFloat(i) * segmentLength)
}
// Second path (circle)
let radius = CGFloat(100.0)
let center = CGPoint(x: 104.0, y: 104.0)
let space = (x: 2.0, y: 2.0)
var circlePath = CGPathCreateMutable()
CGPathMoveToPoint(circlePath, nil, center.x + radius, center.y)
for i in 0...segments {
let x = cos(-CGFloat(i) * angle)
let y = sin(-CGFloat(i) * angle)
CGPathAddLineToPoint(circlePath, nil, center.x + radius * x, center.y + radius * y)
}
I have also uploaded a Swift plaground for you to experiment with, which you can find here
Segments
Now, handling the segments can be a bit tricky, however I propose a relatively naive implementation that might work. Mainly, CAShapeLayer has the following two properties - strokeStart and strokeEnd, which allow controlling the part of the path that is actually stroked.
With this in mind, you could create as many layers as there are segments, assign them all the same path(s) and tweak their respective strokeStart and strokeEnd properties to make it look the way you expect. Somewhat similar to what they do in this post.
Animation
Assuming you have conquered the previous two aspects, the animation aspect should be relatively straight forward, using the two types of paths you have, you can create a simple CABasicAnimation that goes from one to another. I will assume you are familiar with CoreAnimation and its usage (i.e how to properly change model values to match those that are presented etc.).
I will end my answer with a quick animation showing what the end result could look like (minus the segments), I have frozen the animation and am manipulating the timeOffset property of the layer to manually scrub through it.
I hope my answer helps you get closer to the solution you want. It is also important to emphasise that my code examples are just a beginning, you will likely need to tweak the values quite a bit to achieve a satisfying animation (for example, the length of the line should be similar to that of the circumference of the circle).
Skewing, twisting and bending are none trivial transformations on bodies.
These can't be done Core Graphics.
Better draw the chart yourself with CGContextAddArcToPoint in core graphic and mask out the inner circle.
The other (hardcore) way would be using a 3d engine - i.e. scene kit - and apply your chart as texture to it.

How do I find the lowest or highest point on a UIView being dragged with UIAttachmentBehavior?

Depending on where the anchorPoint is with UIAttachmentBehavior, the view can be quite rotated, so it's in more of a diamond shape than a square. In these situations, where it's rotated say 90°, how do I find what the lowest or highest point of this UIView is (in relation to the window)?
It's easy enough when the UIView is a (non-rotated) square, as I can just use CGRectGetMaxY (or min) and the x value doesn't matter, and then use convertPoint, but with the rotation the x value seems to have a real importance, as if I choose maxX, it will tell me the bottom right's point, while minX will give me the bottom left's.
I just want the lowest point that exists in the UIView. How do I get this?
EDIT: Here's some code showing how I'm attempting it currently:
CGPoint lowestPoint = CGPointMake(CGRectGetMinX(weakSelf.imageView.bounds), CGRectGetMaxY(weakSelf.imageView.bounds));
CGPoint convertedPoint = [weakSelf.imageView convertPoint:lowestPoint toView:nil];
The tracking of convertedPoint's y value completely changes depending on what I supply for the x value in lowestPoint's CGPointMake.
The view's frame is its bounding box. Normally you should be careful about using the frame of a transformed view, which is precisely what a rotated-by-UIKit-Dynamics view is. But it does give the info you are after.

Cocoa Touch, set transform identity equal to current transform state

How do I change the transformIdentity. How do we set the transform "zero", or alter the transformIdentity of a view to the current state of the transform of said view.
In other words, I want to scale a view, and then set the current state (say scale of 2.5) to the default scale of the view (scale of 1).
example code:
view.transform = CGAffineTransformMakeScale(1, 2.5);
pseudo code for what I want to do:
view.transform = setTransformIdentityTo:view.currentState;
If I understand correctly transformIdentity is the state at which a scale would be 1, or a rotation would be zero, the default "zero" transform.
NOTE: The reason I want to do this is so that I can set a negative scale transform on only one axis of the view and alway get a flipped view relative to the last state of the view before the flip was invoked.
CGAffineTransformIdentity does reset a view or layer to its original, untransformed state, and thus cannot be redefined.
But if you want your "personal" reset transform, e.g. with a different scale, why don't you simply define it, e.g. by using CGAffineTransform myCGAffineTransformIdentity = CGAffineTransform CGAffineTransformMakeScale (sx,sy);, and apply it to your views?
selectedSticker.transform = CGAffineTransformIdentity;
Seems like this works for what I want to do:
CGAffineTransform trans = CGAffineTransformMakeScale(1, 2.5);
view.transform = CGAffineTransformConcat(selectedSticker.transform, trans);
What you can do, if you want to have your view still be transformed even when its own transform is the identity transform, is to put it inside another view that is transformed. Give the outer view the transform you want for your default; the inner view is the one where you do the actual work.
So, let's say you want your “identity” to be scaled by 2× horizontally. You set your outer view's transform to that transform, and leave it that way, and leave the inner view untransformed. When you want to add further transformation, you add it to the inner view, and when you want to reset it back to your default, you set the inner view's transform back to (true) identity. Your inner view will still scaled (or whatever) by the outer view's transform.
Note: I tried this briefly and found that (a) Auto Layout barfed on it, (b) scaling is outward from the anchor point, which means my outer view's horizontal scale pushed my inner view a little bit out-of-bounds, and (c) changing the outer view's anchor point to CGPointZero produced even further hilarity.
So, while this is theoretically a nice, simple, elegant solution, it may actually be more problematic than it's worth, in which case I recommend what Reinhard Männer suggested.

Resources