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

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.

Related

Text isn't scaling properly in frame

I'm making a flowchart app and I've ran into a problem while scaling shapes containing text in them.
Depending on the scale value the relative width of string changes:
scale 6.0: scale 6.0
scale 1.0:
scale 1.0
scale 0.5:
scale 0.5
Text area class has property logFontSize, which represents constant font size (12.0 in this case).
Scaling function (zoomVal is the new scale):
func zoom(zoomVal: CGFloat){
let newSize = self.logFontSize*zoomVal
self.attributes![NSAttributedString.Key.font] = (self.attributes![NSAttributedString.Key.font] as! UIFont).withSize(newSize)
self.attributedString?.setAttributes(self.attributes, range: NSRange(location: 0, length: self.text!.count))
}
I've also checked: there is no correlation between scale value and relation between frame rectangle (red) height and string height (capHeight, lineHeight etc).
How do I scale text so that the relation between its width and its frame's width remains constant?
This is a feature that improves legibility. Text metrics like size and padding do not have simple, linear relationships. They are tweaked in numerous ways at various sizes, and in font-specific ways, to keep text easy to read.
If you want to linearly scale text, you should render it, and then scale the layer it is drawn in. For your use case, likely the best approach would be to compose a static CATextLayer with CAShapeLayers, and then apply a CAAffineTransform to the entire container CALayer to resize it. This will give you smooth zooming, and will be more performant.

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.

CATransform3D - understanding the transform values

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!

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.

How to determine/calculate where the Y axis tick marks are being plotted in CorePlot?

I'm working with CorePlot to generate a bar graph with horizontal bars (CPTXYGraph and CPTBarPlot).
There are only 10 bars being plotted at any given time, but the labels for them are arbitrarily long. As a result of that the Y axis labels rotation is set to 0.5. For the longest labels there are clipping issues with the label going outside of the left and/or bottom of the plot area.
I've fixed this in the X direction by determining the width of the longest label (as rendered in the appropriate font) and rotated the appropriate way to set the left padding in the plotAreaFrame.
Due to the rotation of the labels, if the plot at the bottom of the graph has a long name it can still extend off the bottom edge of the graph and get clipped there.
I know how tall vertically the rotated label is, but where I'm stuck is trying to determine where in the plot area the axis label is being plotted so that I can determine how much bottom padding is required.
I'm not sure if I should be trying to determine how tall the X axis label section is and then subdividing the remaining height to determine where the ticks should fall, or if there's some other better way to go about it.
The label is offset from end of the nearest tick mark by the labelOffset. The position of the end of the tick mark depends on the tickDirection, tickLabelDirection, and majorTickLength.
There are methods that allow you to convert a point from the plot space coordinate system to the view coordinate system. I've ended up solving the problem with code like the following:
// Tell the graph to lay itself out if it needs to.
[self.graph layoutIfNeeded];
// Create a point that represents 0,1 as plotted on the graph.
NSDecimal plotPoint[2];
plotPoint[CPTCoordinateX] = CPTDecimalFromInt (0);
plotPoint[CPTCoordinateY] = CPTDecimalFromInt (1);
// Convert that point from the plot coordinate system to the view coordinate system
CGPoint point = [self.graph.defaultPlotSpace plotAreaViewPointForPlotPoint: plotPoint];
// If the difference between the height of the rotated label and the position that it
// will be plotted at is at least the bottom padding, then the height is too large,
// so fix the padding.
if (labelHeight - point.y >= self.graph.plotAreaFrame.paddingBottom)
[self.graph.plotAreaFrame setPaddingBottom: (labelHeight - point.y)];
My graphs have a default bottom padding already set as a minimum, allowing this code to bump it up if there isn't enough already.

Resources