Drawing text with CGContextShowGlyphsAtPoint - how to get font dimensions? - objective-c

Hoping this is fairly simple. Basically, I'm drawing some text onto an NSView and need to know the "physical" height and width of the glyphs being drawn.
The font is fixed-width so I don't need to worry about kerning, all I need to do is ensure each glyph is centred horizontally and vertically within its "space"
This isn't the actual code but I've re-written it in a way that should make it easier to understand what I'm trying to achieve.
CGFontRef myFontRef = CGFontCreateWithDataProvider(myFontDataProvider);
CGContextSetFont(thisContext, myFontRef);
CGFloat fontSize = 1.0; //will be changeable later
CGContextSetFontSize(thisContext, fontSize);
CGRect charBounds = CGRectMake(x, y, widthPerChar, heightPerChar);
//paint charBounds with background colour
CGFloat textX = x + 2;
CGFloat textY = y + 5;
CGContextShowGlyphsAtPoint(thisContext, textX, textY, (CGGlyph *)displayedString, 1);
If I was able to calculate the width of the displayed glyph it would be easy to work out what textX and textY should be.
Thanks in advance to anybody willing to assist.

Partly worked it out from this code - here's what I came up with:
CGContextSetTextDrawingMode(thisContext, kCGTextInvisible);
CGContextShowGlyphsAtPoint(thisContext, 1, 1, (const CGGlyph *)"x", 1);
CGPoint postPosition = CGContextGetTextPosition(thisContext);
CGFloat textOffsetX = ((postPosition.x - 1) / 2);
CGFloat textOffsetY = (fontSize * 5);
CGContextSetTextDrawingMode(thisContext, kCGTextFillStroke);
Not a huge fan of doing it like this but it's working for now. At least it can be calculated once for each window resize which isn't too bad.
Thanks for the help though!

You can calculate the width of single glyph in this way:
CGRect units;
CGFontGetGlyphBBoxes(font, &glyph, 1, &units);
float width = units.size.width/CGFontGetUnitsPerEm(font)*fontSize;

Related

Xcode - Round to closest X value considering altered base x/y positions

I'm currently working on a UICollectionViewLayout which is more or less similar to the Garageband iPad Appication - featuring reusable decoration/supplementary views.
One of the main features is gridline snapping - which would enable you to snap the X/Y frame positions of the GREEN cells to the nearest horizontal/vertical gridline.
The issue I'm having, is that the base X/Y position doesn't start at 0,0 because I have a floating column and floating row - so my snapping calculation is wrong because it doesn't consider the floating row/floating column width/height.
Here is an image illustrating my problem:
Here is my code for calculating the snapped positions:
CGPoint cellTopLeft = self.frame.origin;
CGFloat gridlineWidth = 30;
CGFloat floatingColumnWidth = 120; // width of the floating left column
CGFloat floatingRowHeight = 100; // height of the floating top row
CGFloat rowHeight = 100; // height of rows on the left (table 0, table 1, table 2, etc)
float snapped_x = [self closest:cellTopLeft.x toValue:gridlineWidth];
float snapped_y = [self closest:cellTopLeft.y toValue:rowHeight];
- (float)closest:(float)input toValue:(float)value {
return value * floorf((input / value) + 0.5);
}
As you can see by the "Grand 0" green cell that I'm actively dragging, the position is wrong.
Thanks #zrzka - sometimes the seemingly complicated bugs can be the easiest ones to solve, and just takes an extra pair of eyes.
The solution was:
float snapped_x = [self closest:cellTopLeft.x - floatingColumnWidth toValue:gridlineWidth] + floatingColumnWidth
float snapped_y = [self closest:cellTopLeft.y - floatingRowHeight toValue:rowHeight] + floatingRowHeight;

Drawing a Speedometer with Core Graphics on OSX in NSView

I'm trying draw elements of a Speed Gauge using Core Graphics on OSX. I've almost got it but need a little bit of help on the center ticks inside of the gauge. Here is the image of what I'm trying to do:
Here is an image of what I've got so far:
I know how to draw the circle rings and how to draw segments based around the center of the gauge like this:
- (void)drawOuterGaugeRingsInRect:(CGContextRef)contextRef rect:(NSRect)rect {
CGContextSetLineWidth(contextRef,self.gaugeRingWidth);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeOuterRingGray].CGColor);
CGFloat startRadians = 0;
CGFloat endRadians = M_PI*2;
CGFloat radius = self.bounds.size.width/2 - 5;
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render the outer gauge
CGContextStrokePath(contextRef);
//Draw the inner gauge ring.
radius -= self.gaugeRingWidth;
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeInnerRingGray].CGColor);
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render the inner gauge
CGContextStrokePath(contextRef);
radius -= self.gaugeRingWidth;
//Draw and fill the gauge background
CGContextSetFillColorWithColor(contextRef, [MyColors SpeedGaugeCenterFillBlack ].CGColor);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeCenterFillBlack].CGColor);
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render and fill the gauge background
CGContextDrawPath(contextRef, kCGPathFillStroke);
/*BLUE CIRCULAR DIAL */
//Prepare to draw the blue circular dial.
radius -= self.gaugeRingWidth/2;
//Adjust gauge ring width
CGContextSetLineWidth(contextRef,self.gaugeRingWidth/2);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeBlue].CGColor);
CGFloat startingRadians = [MyMathHelper degressToRadians:135];
CGFloat endingRadians = [MyMathHelper degressToRadians:45];
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startingRadians,endingRadians,NO);
//Render the blue gauge line
CGContextStrokePath(contextRef);
}
The code above is called in the drawRect: method in my NSView
The key section is the code here:
- (void)drawInnerDividerLines:(CGContextRef)context rect:(NSRect)rect {
CGFloat centerX = CGRectGetMidX(rect);
CGFloat centerY = CGRectGetMidY(rect);
CGContextSetLineWidth (context, 3.0);
CGContextSetRGBStrokeColor (context, 37.0/255.0, 204.0/255.0, 227.0/255.0, 0.5);
CGFloat destinationX = centerX + (centerY * (cos((135)*(M_PI/180))));
CGFloat destinationY = centerY + (centerX * (sin((135)*(M_PI/180))));
NSPoint destinationPoint = NSMakePoint(destinationX, destinationY);
CGContextMoveToPoint(context, centerX, centerY);
CGContextAddLineToPoint(context, destinationPoint.x, destinationPoint.y);
CGContextStrokePath(context);
}
I understand what is going on here but the problem I'm trying to solve is drawing the little lines, off of the inner blue line that extend toward the center point of the View, but do not draw all the way to the center. I'm a little unsure on how to modify the math and drawing logic to achieve this. Here is the unit circle I based the angles off of for Core Graphics Drawing.
The main problems I'm trying to solve are:
How to define the proper starting point off of the light blue inner line as a staring point for each gauge tick. Right now, I'm drawing the full line from the center to the edge of the gauge.
How to control the length of the tick gauge as it draws pointed toward the center off of it's origin point on the blue line.
Any tips or advice that would point in me in the right direction to solve this would be appreciated.
I recommend using vectors. You can find a line to any point on the circle given an angle by calculating:
dirX = cos(angle);
dirY = sin(angle);
startPt.x = center.x + innerRadius * dirX;
startPt.y = center.y + innerRadius * dirY;
endPt.x = center.x + outerRadius * dirX;
endPt.y = center.y + outerRadius * dirY;
You can then plot a line between startPt and endPt.
Any tips or advice that would point in me in the right direction to solve this would be appreciated.
Given a point on the circumference of your circle at a certain angle around the centre you can form a right angled triangle, the radius is the hypotenuse, and the other two sides being parallel to the x & y axes (ignore for a moment the degenerate case where the point is at 0, 90, 180 or 270 deg). Given that with the sin & cos formula (remember SOHCAHTOA from school) and some basic math you can calculate the coordinates of the point, and using that draw a radius from the centre to the point.
The end points of a "tick" mark just lie on circles of different radii, so the same math will give you the end points and you can draw the tick. You just need to decide the radii of these circles, i.e. the distance along your original radius the end points of the tick should be.
HTH
Another approach to avoid the trigonometry is to rotate the transformation matrix and just draw a vertical or horizontal line.
// A vertical "line" of width "width" along the y axis at x==0.
NSRect tick = NSMakeRect(-width / 2.0, innerRadius, width, outerRadius - innerRadius);
NSAffineTransform* xform = [NSAffineTransform transform];
// Move the x and y axes to the center of your speedometer so rotation happens around it
[xform translateXBy:center.x yBy:center.y];
// Rotate the coordinate system so that straight up is actually at your speedometer's 0
[xform rotateByDegrees:135];
[xform concat];
// Create a new transform to rotate back around for each tick.
xform = [NSAffineTransform transform];
[xform rotateByDegrees:-270.0 / numTicks];
for (int i = 0; i < numTicks; i++)
{
NSRectFill(tick);
[xform concat];
}
You probably want to wrap this in [NSGraphicsContext saveGraphicsState] and [NSGraphicsContext restoreGraphicsState] so the transformation matrix is restored when you're done.
If you want two different kinds of tick marks (major and minor), then have two different rects and select one based on i % 10 == 0 or whatever. Maybe also toggle the color. Etc.

Rotate around the center of a CCLabelTTF as achnor point

I want to rotate a CCLabelTTF around it's center.
But it doesn't look like it. It does look more like a rotation at the bottom of the CCLabelTTF.
Code:
CCLabelTTF *aLabel ... init/addChild and so on
CCRotateBy *rotateLabelA = [[CCRotateBy alloc] initWithDuration:0.5f angle:-60.0f];
aLabel.string = #"0";
aLabel.anchorPoint = ccp(0.5f, 0.5f);
[aLabel runAction:rotateLabelA];
How to rotate a letter around its visible center, if it is a CCLabelTTF?
I was able to make the boundary box of a CCLabelTTF visible:
As seen in the image, the bounding box is much bigger. But there isn't a formula to determine the middle of the letter.
If you set anchorPoint = cpp(0.5f,0.5f) to some ccNode object, it will rotate around its center, which is calculated using boundingBox property.
The problem is the label's boundingBox.size.height differs with it's actual height. That is why it rotates not around the center.
I am not sure in such a manual solution, but it worked for me someday.
CCLabelTTF *label = [CCLabelTTF labelWithString:#"0" fontName:#"Marker Felt"fontSize:24];
label.position = ccp(winSize.width /2.0f, winSize.height / 2.0f);
float fontSize = label.fontSize; // actual Font size
float labelHeight = label.contentSize.height; // actual label height ( the same as boundingBox.size.height
float offset = (labelHeight - fontSize - (labelHeight - fontSize) / 2.0f) / labelHeight / 2.0f;
label.anchorPoint = ccp(0.5f, 0.5f + offset);
[layer addChild:label];
[label runAction:[CCRotateBy actionWithDuration:10.0f angle:-360]];
I found out how to find the middle point of an CCLabelTTF:
float fontSize = bLabel.fontSize; // actual Font size in pixels
float labelHeight = bLabel.contentSize.height; // actual label height ( the same as boundingBox.size.height )
float offset = labelHeight - fontSize; // the free room under the font
float halfFontSize = fontSize / 2;
float percentMiddleOfFont = (halfFontSize + offset) / labelHeight;
bLabel.anchorPoint = ccp(0.5f, percentMiddleOfFont);

Drawing board/grid with Cocoa

I'm writing a small boardgame for Mac OS X using Cocoa. I the actual grid is drawn as follows:
- (void)drawRect:(NSRect)rect
{
for (int x=0; x < GRIDSIZE; x++) {
for (int y=0; y < GRIDSIZE; y++) {
float ix = x*cellWidth;
float iy = y*cellHeight;
NSColor *color = (x % 2 == y % 2) ? boardColors[0] : boardColors[1];
[color set];
NSRect r = NSMakeRect(ix, iy, cellWidth, cellHeight);
NSBezierPath *path = [NSBezierPath bezierPath];
[path appendBezierPathWithRect:r];
[path fill];
[path stroke];
}
}
}
This works great, except that I see some errors in colors between the tiles. I guess this is due to some antialiasing or similar. See screenshots below (hopefully you can also see the same problems... its some black lines where the tiles overlap):
Therefore I have these questions:
Is there any way I can remove these graphical artefacts while still maintaining a resizable/scalable board?
Should I rather use some other graphical library like Core Graphics or OpenGL?
Update:
const int GRIDSIZE = 16;
cellWidth = (frame.size.width / GRIDSIZE);
cellHeight = (frame.size.height / GRIDSIZE);
If you want crisp rectangles you need to align coordinates so that they match the underlying pixels. NSView has a method for this purpose: - (NSRect)backingAlignedRect:(NSRect)aRect options:(NSAlignmentOptions)options. Here's a complete example for drawing the grid:
const NSInteger GRIDSIZE = 16;
- (void)drawRect:(NSRect)dirtyRect {
for (NSUInteger x = 0; x < GRIDSIZE; x++) {
for (NSUInteger y = 0; y < GRIDSIZE; y++) {
NSColor *color = (x % 2 == y % 2) ? [NSColor greenColor] : [NSColor redColor];
[color set];
[NSBezierPath fillRect:[self rectOfCellAtColumn:x row:y]];
}
}
}
- (NSRect)rectOfCellAtColumn:(NSUInteger)column row:(NSUInteger)row {
NSRect frame = [self frame];
CGFloat cellWidth = frame.size.width / GRIDSIZE;
CGFloat cellHeight = frame.size.height / GRIDSIZE;
CGFloat x = column * cellWidth;
CGFloat y = row * cellHeight;
NSRect rect = NSMakeRect(x, y, cellWidth, cellHeight);
NSAlignmentOptions alignOpts = NSAlignMinXNearest | NSAlignMinYNearest |
NSAlignMaxXNearest | NSAlignMaxYNearest ;
return [self backingAlignedRect:rect options:alignOpts];
}
Note that you don't need stroke to draw a game board. To draw pixel aligned strokes you need to remember that coordinates in Cocoa actually point to lower left corners of pixels. To crisp lines you need to offset coordinates by half a pixel from integral coordinates so that coordinates point to centers of pixels. For example to draw a crisp border for a grid cell you can do this:
NSRect rect = NSInsetRect([self rectOfCellAtColumn:column row:row], 0.5, 0.5);
[NSBezierPath strokeRect:rect];
First, make sure your stroke color is not black or gray. (You're setting color but is that stroke or fill color? I can never remember.)
Second, what happens if you simply fill with green, then draw red squares over it, or vice-versa?
There are other ways to do what you want, too. You can use the CICheckerboardGenerator to make your background instead.
Alternately, you could also use a CGBitmapContext that you filled by hand.
First of all, if you don't actually want your rectangles to have a border, you shouldn't call [path stroke].
Second, creating a bezier path for filling a rectangle is overkill. You can do the same with NSRectFill(r). This function is probably more efficient and I suspect less prone to introduce rounding errors to your floats – I assume you realize that your floats must not have a fractional part if you want pixel-precise rectangles. I believe that if the width and height of your view is a multiple of GRIDSIZE and you use NSRectFill, the artifacts should go away.
Third, there's the obvious question as to how you want your board drawn if the view's width and height are not a multiple of GRIDSIZE. This is of course not an issue if the size of your view is fixed and a multiple of that constant. If it is not, however, you first have to clarify how you want the possible remainder of the width or height handled. Should there be a border? Should the last cell in the row or column take up the remainder? Or should it rather be distributed equally among the cells of the rows or columns? You might have to accept cells of varying width and/or height. What the best solution for your problem is, depends on your exact requirements.
You might also want to look into other ways of drawing a checkerboard, e.g. using CICheckerboardGenerator or creating a pattern color with an image ([NSColor colorWithPatternImage:yourImage]) and then filling the whole view with it.
There's also the possibility of (temporarily) turning off anti-aliasing. To do that, add the following line to the beginning of your drawing method:
[[NSGraphicsContext currentContext] setShouldAntialias:NO];
My last observation is about your general approach. If your game is going to have more complicated graphics and animations, e.g. animated movement of pieces, you might be better off using OpenGL.
As of iOS 6, you can generate a checkerboard pattern using CICheckerboardGenerator.
You'll want to guard against the force unwraps in here, but here's the basic implementation:
var checkerboardImage: UIImage? {
let filter = CIFilter(name: "CICheckerboardGenerator")!
let width = NSNumber(value: Float(viewSize.width/16))
let center = CIVector(cgPoint: .zero)
let darkColor = CIColor.red
let lightColor = CIColor.green
let sharpness = NSNumber(value: 1.0)
filter.setDefaults()
filter.setValue(width, forKey: "inputWidth")
filter.setValue(center, forKey: "inputCenter")
filter.setValue(darkColor, forKey: "inputColor0")
filter.setValue(lightColor, forKey: "inputColor1")
filter.setValue(sharpness, forKey: "inputSharpness")
let context = CIContext(options: nil)
let cgImage = context.createCGImage(filter.outputImage!, from: viewSize)
let uiImage = UIImage(cgImage: cgImage!, scale: UIScreen.main.scale, orientation: UIImage.Orientation.up)
return uiImage
}
Apple Developer Docs
Your squares overlap. ix + CELLWIDTH is the same coordinate as ix in the next iteration of the loop.
You can fix this by setting the stroke color explicitly to transparent, or by not calling stroke.
[color set];
[[NSColor clearColor] setStroke];
or
[path fill];
// not [path stroke];

iOS: UIPickerView default dimensions

I would like to know the width of the dark grey frame on either side of the inside picker part and the width of the separators between components. This would be at default settings (eg. what's shown in the .xib). Or, how to find such values programmatically. Thank you
To clarify, I'm looking for what the "suggested minimums" might be for those values. I'm putting my UIPickerView in a popover, and the UIPickerView is wider than 320 px (which is what the .xib gives as the "default"). I would like to know these values so I can add them to the popover's width to make sure it doesn't cut off components on the right side of the UIPickerView.
Well this can be a little tricky since the Picker can have a dynamic number of components. So in order to find the widths you have to take into account the number of components. This can be done like so:
NSInteger n = picker.numberOfComponents;
const CGFloat separatorWidth = 8.0f;
const CGFloat sectionExceedWidth = -2.0f;
CGFloat totalWidth = picker.bounds.size.width;
CGFloat panesWidth = totalWidth - separatorWidth * (n - 1);
for (NSInteger i = 0; i < n; i++) {
CGFloat sectionWidth = [picker rowSizeForComponent:i].width + sectionExceedWidth;
panesWidth -= sectionWidth;
}
CGFloat leftPaneWidth = ceilf(panesWidth * 0.5f);
CGFloat rightPaneWidth = panesWidth - leftPaneWidth;
CGFloat totalHeight = picker.bounds.size.height;
CGRect totalRect = CGRectMake(0, 0, totalWidth, totalHeight);
Where the left and right panes widths are found and the separator size is static.
This was pulled from here.