How to calculate the height of NSAttributedString, given width and number of lines? - nsattributedstring

I want to display 3 lines of NSAttributedString. Is there a way to figure out the needed height, based on width and number of lines?
And I don't want to create a UILabel to do the size calculation, since I want the calculation to be done in background thread.

I wonder why this is still unanswered. Anyhow, here's the fastest method that works for me.
Make an NSAttributedString Category called "Height". This should generate two files titled "NSAttributedString+Height.{h,m}"
In the .h file:
#interface NSAttributedString (Height)
-(CGFloat)heightForWidth:(CGFloat)width;
#end
In the .m file:
-(CGFloat)heightForWidth:(CGFloat)width
{
return ceilf(CGRectGetHeight([self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
context:nil])) + 1;
}
Here's what's happening:
boundRectWithSize:options:context get's a rect constrained to a width you pass to the method. The NSStringDrawingUsesLineFragmentOrigin option tells it to expect multiline string.
Then we fetch the height parameter from that rect.
In iOS 7, this method returns decimals. We need a round figure. ceilf helps with that.
We add an extra unit to the returning value.
Here's how to use it
NSAttributedString *string = ...
CGFloat height = [string heightForWidth:320.0f];
You can use that height for your layout computations.

The answer by #dezinezync answers half of the question. You'll just have to calculate the maximum size allowed for your UILabel with the given width and number of lines.
First, get the height allowed based on number of lines:
let maxHeight = font.lineHeight * numberOfLines
Then calculate the bounding rect of the text you set based on the criteria:
let labelStringSize = yourText.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), maxHeight),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size

There is a method in TTTAttributedLabel called
+ (CGSize)sizeThatFitsAttributedString:withConstraints:limitedToNumberOfLines:
Basically,this method use some Core Text API to calculate the height, the key function is
CGSize CTFramesetterSuggestFrameSizeWithConstraints(
CTFramesetterRef framesetter,
CFRange stringRange,
CFDictionaryRef __nullable frameAttributes,
CGSize constraints,
CFRange * __nullable fitRange )
which I think ,is also used by
- (CGRect)textRectForBounds:limitedToNumberOfLines:
this is a workaround and I think there are better way...
static UILabel *label;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
label = [UILabel new];
});
label.attributedText = givenAttributedString;
CGRect rect = CGRectMake(0,0,givenWidth,CGFLOAT_MAX)
CGFloat height = [label textRectForBounds:rect
limitedToNumberOfLines:2].size.height;

Related

Matter-js - How to get width and height of rectangle?

Matter-js - How to get width and height of rectangle ?
I need to know is there distance return method implemented in Matter-js .
// part.vertices[0] and part.vertices[1]
I wanna integrate tiles option.
This is how looks critical part (i use override function for Render.bodies it is most interest for me) .:
for (let x = 0; x < this.tiles; x++) {
c.drawImage(
texture,
texture.width * -part.render.sprite.xOffset * part.render.sprite.xScale,
texture.height * -part.render.sprite.yOffset * part.render.sprite.yScale,
texture.width * part.render.sprite.xScale,
texture.height * part.render.sprite.yScale);
}
const { min, max } = part.bounds
it will contain what you need in { x, y }
just substract max.x - min.x & max.y - min.y
I went with a solution very similar to the following:
var width = 30;
var height = 30;
var rect = Bodies.rectangle(150, 100, width, height, {density:0.01, className:"brick", width:width, height:height});
console.log(rect.className, rect.width); // "brick", 30
I decided to carry the original width/height information along with other custom properties such as className
The reason why is because bounds is affected by the rotation of any non perfectly-circular object eg. a rotated rectangle's bounds could be up to ~30% wider than it's actual width.
There are two solutions that I've found.
1- Create a class to wrap the matter.js body, which will also hold onto the height and width. ie:
class rectWrapper {
constructor(x, y, width, height, options){
this.width = width
this.height = height
this.body = Matter.Bodies.rectangle(x, y, width, height, options)
}
}
2- Another way is to use the magic of math to determine the distance between two coordinate points, using Body.vertices[0] and Body.vertices[1] for the width, and Body.vertices[0] and Body.vertices[3] for height. This would also account for any rotation. This link explains it clearly, for 2 and 3 dimensions:
https://sciencing.com/calculate-distance-between-two-coordinates-6390158.html
I would recommend writing your own "utility function" to do this. A heavy handed example might look like this:
function distance(x1, y1, x2, y2){
var x = Math.abs(x1-x2)
var y = Math.abs(y1-y2)
return Math.sqrt((x*x)+(y*y))
}
So a call might look like:
var rect = Matter.Bodies.rectangle(0,0,10,50)
var width = distance(rect.vertices[0].x, rect.verticies[0].y, rect.vertices[1].x, rect.vertices[1].y)
var height = distance(rect.vertices[0].x, rect.vertices[0].y, rect.vertices[3].x, rect.vertices[3].y)
Alternatively, if you happen to be using p5.js as your renderer, you can use p5.dist() which takes x1, y1, x2, y2 as arguments and returns the distance (basically the same as the function above):
https://p5js.org/reference/#/p5/dist
Note, this will only work for rectangles. If you're using different kinds of geometry, I would probably just make a wrapper class myself.

PdfSharp: Why do I need to multiply positions and sizes by 1.25 to get the right result?

I am evaluating PdfSharp to create PDF documents. While comparing it with MigraDoc I figured that I had to multiply each position (x, y) or size by 1.25 to get the intended result. For example if I set the page margins to 2 cm without the correction, I get margins of roughly 1.6 cm.
page.TrimMargins = new TrimMargins
{
All = XUnit.FromCentimeter(2)
};
When I multiply 2 with 1.25 I get the intended 2 cm margins:
page.TrimMargins = new TrimMargins
{
All = XUnit.FromCentimeter(2 * 1.25)
};
Same is with font sizes. I have to multiply the size by 1.25 to get the same size as MigraDoc or even Word would print.
My system does not have a custom scaling or a text size other than 100% by the way (my guess was this could be the cause).
Can someone explain what's going on here?
Edit:
With the help of TomasH I found out that when printing without auto scaling the sizing was perfect. PdfSharp obviously creates PDF documents too large. When doing the same with MigraDoc the PDF is also a bit too large as I found out, but only on a much smaller scale. The question that remains is why the document is too large and what MigraDoc does to correct the PDF size.
Here is my complete test code that only gives the correct positioning and sizing with the correction factor:
using (PdfDocument document = new PdfDocument())
{
// Create an empty page size A4 with defined margins
PdfPage page = CreatePage(document);
using (XGraphics graphics = XGraphics.FromPdfPage(page))
{
const double sizeCorrectionFactor = 1.25;
// Define the page margins. They must be multiplied by 1.25 to be correct!?
page.TrimMargins = new TrimMargins
{
All = XUnit.FromCentimeter(2 * sizeCorrectionFactor)
};
// Draw a string. The font size needs to be multiplied by 1.25 to be correct!?
double x = 0;
double y = 0;
graphics.DrawRectangle(XPens.Black, XBrushes.White, 0, 0, page.Width, page.Height);
graphics.DrawString("PdfSharp Measure Demo", new XFont("Verdana", 20 * sizeCorrectionFactor), XBrushes.Navy, x, y, XStringFormats.TopLeft);
// Draw a rectangle. Position and size must be multiplied by 1.25 to be correct!?
x = XUnit.FromCentimeter(2 * sizeCorrectionFactor);
y = XUnit.FromCentimeter(2 * sizeCorrectionFactor);
double width = XUnit.FromCentimeter(5 * sizeCorrectionFactor);
double height = XUnit.FromCentimeter(5 * sizeCorrectionFactor);
graphics.DrawRectangle(XPens.Red, XBrushes.Silver, x, y, width, height);
}
string pdfFilePath = Path.GetTempFileName() + ".pdf";
document.Save(pdfFilePath);
Process.Start(pdfFilePath);
}
I found the answer: I got the meaning of the (not well documented) TrimMargins property wrong. Setting the trim margins obviously adds the size of the margins to the width or height of the page. This means if trim margins are set, the page size is too large and usually gets scaled down when displaying or printing it. I set 2 cm for the trim margins, making the page obviously 1.25 times too large. The solution is to let all trim margins be 0 and account for any desired page margins in the printing code instead.

Replacement for sizeWithFont:ForWidth:lineBreakMode:

Many of the methods I had been using to determine layout of printed strings for creation of complex pdf documents have been deprecated in iOS7. Documentation calls out the same method to use as replacement for all the sizeWithFont methods that are deprecated:
boundingRectWithSize:options:attributes:
That is fine for sizeWithFont:ConstrainedTosize:lineBreakMode but what if I want my string on one line only? I don't know what to use for max height so I do not have a rect to hand over as a value for the first parameter.
Here is what I have when limiting to a given size.
CGFloat maxHeightAllowable = _maxHeight;
CGSize issueTitleMaxSize = CGSizeMake(_issueListTitleColWidth - (kColumnMargin *2), maxHeightAllowable);
NSDictionary *issueTitleAttributes = [NSDictionary dictionaryWithObjectsAndKeys:_bodyFont, NSFontAttributeName, nil];
CGRect issueTitleRect = CGRectIntegral([issueTitleText boundingRectWithSize:issueTitleMaxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:issueTitleAttributes context:nil]);
CGSize issueTitleSize = issueTitleRect.size;
How would I use this same method if I don't know the maxHeight, or actually, height for one line is exactly what I am trying to find out?
I see why they are pushing towards compatibility for the NSAttributed strings and auto layout but why deprecate these? The replacement, in my case, now takes 4 or 5 steps where it used to be 1 or 2.
Using the lineHeight property of font, as suggested by Mr T, I made these methods in a category that greatly simplifies my replacement.
#import "NSString+SizingForPDF.h"
#implementation NSString (SizingForPDF)
-(CGSize)integralSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)maxSize
{
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGRect rect = CGRectIntegral([self boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil]);
return rect.size;
}
-(CGSize)integralSizeWithFont:(UIFont *)font maxWidth:(CGFloat)maxWidth numberOfLines:(NSInteger)lines
{
if (lines == 0) {
lines = 1;
}
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
CGFloat height = font.lineHeight * lines;
CGSize maxsize = CGSizeMake(maxWidth, height);
CGRect rect = CGRectIntegral([self boundingRectWithSize:maxsize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:attributes context:nil]);
return rect.size;
}
#end
If you were just looking for the height of one line, couldn't you just use your font's lineHeight property? I use that to set the height of my labels or properly anticipate height of elements without any issues. I'm not certain if pdf documents are different in this regard.
Additionally, I believe those functions were deprecated because that series of NSString+UIKit functions (sizeWithFont:..., etc) were based on the UIStringDrawing library, which wasn't thread safe. If you tried to run them not on the main thread (like any other UIKit functionality), you'll get unpredictable behaviors. In particular, if you ran the function on multiple threads simultaneously, it'll probably crash your app. This is why in iOS 6, they introduced a the boundingRectWithSize:... method for NSAttributedStrings. This was built on top of the NSStringDrawing libraries and is thread safe.
On that note, if you were only supporting iOS 6 and iOS 7, then I would definitely change all of your NSString's sizeWithFont:... to the NSAttributeString's boundingRectWithSize. It'll save you a lot of headache if you happen to have a weird multi-threading corner case! Here's how I converted NSString's sizeWithFont:constrainedToSize::
What used to be:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
CGSize size = [text sizeWithFont:font
constrainedToSize:(CGSize){width, CGFLOAT_MAX}];
Can be easily replaced with:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:text
attributes:#
{
NSFontAttributeName: font
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
Please note the documentation mentions:
In iOS 7 and later, this method returns fractional sizes (in the size
component of the returned CGRect); to use a returned size to size
views, you must use raise its value to the nearest higher integer
using the ceil function.
So to pull out the calculated height or width to be used for sizing views, I would use:
CGFloat height = ceilf(size.height);
CGFloat width = ceilf(size.width);

How to do Joint tracking in Kinect with a scaled Image

I trying to do some Joint Tracking with kinect (just put a ellipse inside my right hand) everything works fine for a default 640x480 Image, i based myself in this channel9 video.
My code, updated to use the new CoordinateMapper classe is here
...
CoordinateMapper cm = new CoordinateMapper(this.KinectSensorManager.KinectSensor);
ColorImagePoint handColorPoint = cm.MapSkeletonPointToColorPoint(atualSkeleton.Joints[JointType.HandRight].Position, ColorImageFormat.RgbResolution640x480Fps30);
Canvas.SetLeft(elipseHead, (handColorPoint.X) - (elipseHead.Width / 2)); // center of the ellipse in center of the joint
Canvas.SetTop(elipseHead, (handColorPoint.Y) - (elipseHead.Height / 2));
This works. The question is:
How to do joint tracking in a scaled image, 540x380 for example?
The solution for this is pretty simple, i fugured it out.
What a need to do is find some factor to apply to the position.
This factor can be found takin the atual ColorImageFormat of the Kinect and dividing by the desired size, example:
Lets say i am working with the RgbResolution640x480Fps30 format and my Image (ColorViewer) have 220x240. So, lets find the factor for X:
double factorX = (640 / 220); // the factor is 2.90909090...
And the factor for y:
double factorY = (480/ 240); // the factor is 2...
Now, i adjust the position of the ellipse using this factor.
Canvas.SetLeft(elipseHead, (handColorPoint.X / (2.909090)) - (elipseHead.Width / 2));
Canvas.SetTop(elipseHead, (handColorPoint.Y / (2)) - (elipseHead.Height / 2));
I've not used the CoordinateMapper yet, and am not in front on my Kinect at the moment, so I'll toss out this first. I'll see about an update when I get working with the Kinect again.
The Coding4Fun Kinect Toolkit has a ScaleTo extension as part of the library. This adds the ability to take a joint and scale it to any display resolution.
The scaling function looks like this:
private static float Scale(int maxPixel, float maxSkeleton, float position)
{
float value = ((((maxPixel / maxSkeleton) / 2) * position) + (maxPixel/2));
if(value > maxPixel)
return maxPixel;
if(value < 0)
return 0;
return value;
}
maxPixel = the width or height, depending on which coordinate your scaling.
maxSkeleton = set this to 1.
position = the X or Y coordinate of the joint you want to scale.
If you were to just include the above function you could call it like so:
Canvas.SetLeft(e, Scale(640, 1, joint.Position.X));
Canvas.SetTop(e, Scale(480, 1, -joint.Position.Y));
... replacing your 640 & 480 with a different scale.
If you include the Coding4Fun Kinect Toolkit, instead of re-writing code, you could just call it like so:
scaledJoin = rawJoint.ScaleTo(640, 480);
... then plug in what you need.

How do I get the visual width and height of a rotated component?

I'm playing around with code like this:
<s:Button id="test" label="test" transformX="{Math.floor(test.width/2)}" rotationY="20" x="20" y="20" />
The button is rotated on the Y axis and the rotate pivot is in the middle of the button.
This will create a button that looks something like this:
(source: jeffryhouser.com)
The rotated button is, visually, filling a different space than the x, y, height, and width values would you have believe.
The "A" value in my image is the height of the button. But, what I want to use for calculation and placement purposes is the B value.
Additionally, I'd like to perform similar calculations with the width; getting the width from the top right corner to the bottom left corner.
How do I do this?
I put together a sample to show off the various approaches for calculating this that people are suggesting. The source code is also available. Nothing is quite working like I'd expect. For example, turn the rotationSlider to 85. The button is effectively invisible, yet all approaches are still giving it height and width.
My math may be a bit rusty, but this is how I would find the answer :
You would extend a right-triangle from the right edge of the button to the bottom-most point of the diagram you have (A-B). You can then use the Law of Sines to get three angles : 90', 20' and 70' (90 will always be there, and then your variable - 180 for the third angle).
You can then use the following formula to find your answer :
B = ((button.width * sin(button.rotationY)) / (sin(90 -button.rotationY)) + (button.height)
getBounds(..) and getRect(..) are supposed to be the methods for getting the width and height of transformed objects.
Not tried them in Flex 4 yet, but they always worked for me in Flex 3.
The answer was in one of the comments from James Ward on this question and is located at this blog post.
The one thing the blog post doesn't say is that in many cases, the perspectiveProjection property of the transform property on the class in question will be null. The linked to example took care of this by setting the maintainProjectionCenter property to true. But, you could also create a new perspectiveProjection object like this:
object.transform.perspectiveProjection = new PerspectiveProjection();
I wrapped up the function from evtimmy into a class:
/**
* DotComIt/Flextras
* Utils3D.as
* Utils3D
* jhouser
* Aug 5, 2010
*/
package com.flextras.coverflow
{
import flash.geom.Matrix3D;
import flash.geom.PerspectiveProjection;
import flash.geom.Rectangle;
import flash.geom.Utils3D;
import flash.geom.Vector3D;
public class TransformUtilities
{
public function TransformUtilities()
{
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
//----------------------------------
// projectBounds
//----------------------------------
// info from
// http://evtimmy.com/2009/12/calculating-the-projected-bounds-using-utils3dprojectvector/
/**
* Method retrieved from
* http://evtimmy.com/2009/12/calculating-the-projected-bounds-using-utils3dprojectvector/
*
* #param bounds: The rectangle that makes up the object
* #param matrix The 3D Matrix of the item
* #param the projection of the item's parent.
*/
public static function projectBounds(bounds:Rectangle,
matrix:Matrix3D,
projection:PerspectiveProjection):Rectangle
{
// Setup the matrix
var centerX:Number = projection.projectionCenter.x;
var centerY:Number = projection.projectionCenter.y;
matrix.appendTranslation(-centerX, -centerY, projection.focalLength);
matrix.append(projection.toMatrix3D());
// Project the corner points
var pt1:Vector3D = new Vector3D(bounds.left, bounds.top, 0);
var pt2:Vector3D = new Vector3D(bounds.right, bounds.top, 0)
var pt3:Vector3D = new Vector3D(bounds.left, bounds.bottom, 0);
var pt4:Vector3D = new Vector3D(bounds.right, bounds.bottom, 0);
pt1 = Utils3D.projectVector(matrix, pt1);
pt2 = Utils3D.projectVector(matrix, pt2);
pt3 = Utils3D.projectVector(matrix, pt3);
pt4 = Utils3D.projectVector(matrix, pt4);
// Find the bounding box in 2D
var maxX:Number = Math.max(Math.max(pt1.x, pt2.x), Math.max(pt3.x, pt4.x));
var minX:Number = Math.min(Math.min(pt1.x, pt2.x), Math.min(pt3.x, pt4.x));
var maxY:Number = Math.max(Math.max(pt1.y, pt2.y), Math.max(pt3.y, pt4.y));
var minY:Number = Math.min(Math.min(pt1.y, pt2.y), Math.min(pt3.y, pt4.y));
// Add back the projection center
bounds.x = minX + centerX;
bounds.y = minY + centerY;
bounds.width = maxX - minX;
bounds.height = maxY - minY;
return bounds;
}
}
}
Although that is the answer to my question, I'm not sure if it was the solution to my problem. Thanks everyone!

Resources