Perspective transform on UILabel - uilabel

I'm trying to add some perspective on a UILabel, to make it display as if it's painted over an angled face.
Here's my test label:
And after applying the transform:
My code:
#implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100.f, 250.f, 100.f, 30.f)];
label.text = #"Hello";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor greenColor];
[label tiltDegrees:20.f];
[self.view addSubview:label];
[label release];
}
#end
#implementation UIView (Perspective)
-(void) tiltDegrees:(CGFloat)degrees {
CATransform3D aTransform = CATransform3DIdentity;
CGFloat zDistance = 100; // affects the sharpness of the transform
aTransform.m34 = 1.0 / -zDistance;
aTransform = CATransform3DRotate(aTransform, degrees * M_PI / 180.0f, 1.0f, 0.0f, 0.0f);
self.layer.transform = aTransform;
}
#end
I'm stuck with a bunch of problems:
The text inside the label doesn't seem to apply the transformation in the same way as the UILabel itself does. It's out of frame (clipped), not centered, and the geometry doesn't seem right. Maybe size is wrong too?
It is blurred. How could I apply the transform on the text vector before it is rasterized. I think that would produce crisp results.
I can't seem to work out the coordination between zDistance and the degrees of rotation, so that they result in a correct perspective. How can I calculate zDistance correctly based on degrees?
Any help to solve (1) (2) (3) would be greatly appreciated.
Many Thanks

I don't know if you already solved this, but the problem is basically that your text label is passing through the gray layer behind it, hence why it seems to clip in the middle of the text.
Translate the text layer towards the camera to solve this problem.

Related

UIButton displaying a triangle

I have a UIButton and i want it to display a triangle. Is there a function to make it a triangle? Since im not using a UIView class im not sure how to make my frame a triangle.
ViewController(m):
- (IBAction)makeTriangle:(id)sender {
UIView *triangle=[[UIView alloc] init];
triangle.frame= CGRectMake(100, 100, 100, 100);
triangle.backgroundColor = [UIColor yellowColor];
[self.view addSubview: triangle];
Do i have to change my layer or add points and connect them to make a triangle with CGRect?
If im being unclear or not specific add a comment. Thank you!
A button is a subclass of UIView, so you can make it any shape you want using a CAShape layer. For the code below, I added a 100 x 100 point button in the storyboard, and changed its class to RDButton.
#interface RDButton ()
#property (strong,nonatomic) UIBezierPath *shape;
#end
#implementation RDButton
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.titleEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0); // move the title down to make it look more centered
self.shape = [UIBezierPath new];
[self.shape moveToPoint:CGPointMake(0,100)];
[self.shape addLineToPoint:CGPointMake(100,100)];
[self.shape addLineToPoint:CGPointMake(50,0)];
[self.shape closePath];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = self.shape.CGPath;
shapeLayer.fillColor = [UIColor yellowColor].CGColor;
shapeLayer.strokeColor = [UIColor blueColor].CGColor;
shapeLayer.lineWidth = 2;
[self.layer addSublayer:shapeLayer];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self.shape containsPoint:[touches.anyObject locationInView:self]])
[super touchesBegan:touches withEvent:event];
}
The touchesBegan:withEvent: override restricts the action of the button to touches within the triangle.
A view's frame is always a rect, which is a rectangle. Even if you apply a transform to it so it no longer looks like a rectangle, the view.frame property will still be a rectangle -- just the smallest possible rectangle that contains the new shape you have produced.
So if you want your UIButton to look like a triangle, the simplest solution is probably to set its type to UIButtonTypeCustom and then to set its image to be a png which shows a triangle and is transparent outside of the triangle.
Then the UIButton itself will actually be rectangle, but will look like a triangle.
If you want to get fancy, you can also customize touch delivery so that touches on the transparent part of the PNG are not recognized (as I believe they would be by default), but that might be a bit trickier.

Cocoa: How to draw inset text as in Mail.app?

How can I draw this style of text in Cocoa (OS X)? It seems to be used in several Apple apps including Mail (as pictured above) and several places in Xcode sidebars. I've looked around but haven't been able to find any resources suggesting how to reproduce this specific style of text. It looks like an inset shadow and my first guess was to try using an NSShadow with the blur radius set to a negative value but apparently only positive values are allowed. Any ideas?
I have some code that draws an embossed cell (originally written Jonathon Mah, I believe). It might not do exactly what you want but it'll give you a place to start:
#implementation DMEmbossedTextFieldCell
#pragma mark NSCell
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView;
{
/* This method copies the three-layer method used by Safari's error page. That's accessible by forcing an
* error (e.g. visiting <foo://>) and opening the web inspector. */
// I tried to use NSBaselineOffsetAttributeName instead of shifting the frame, but that didn't seem to work
const NSRect onePixelUpFrame = NSOffsetRect(cellFrame, 0.0, [NSGraphicsContext currentContext].isFlipped ? -1.0 : 1.0);
const NSRange fullRange = NSMakeRange(0, self.attributedStringValue.length);
NSMutableAttributedString *scratchString = [self.attributedStringValue mutableCopy];
BOOL overDark = (self.backgroundStyle == NSBackgroundStyleDark);
CGFloat (^whenLight)(CGFloat) = ^(CGFloat b) { return overDark ? 1.0 - b : b; };
// Layer 1
[scratchString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithCalibratedWhite:whenLight(1.0) alpha:1.0] range:fullRange];
[scratchString drawInRect:cellFrame];
// Layer 2
BOOL useGradient = NO; // Safari 5.2 preview has switched to a lighter, solid color look for the detail text. Since we use the same class, use bold-ness to decide
if (self.attributedStringValue.length > 0) {
NSFont *font = [self.attributedStringValue attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL];
if ([[NSFontManager sharedFontManager] traitsOfFont:font] & NSBoldFontMask)
useGradient = YES;
}
NSColor *solidShade = [NSColor colorWithCalibratedHue:200/360.0 saturation:0.03 brightness:whenLight(0.41) alpha:1.0];
[scratchString addAttribute:NSForegroundColorAttributeName value:solidShade range:fullRange];
[scratchString drawInRect:onePixelUpFrame];
// Layer 3 (Safari uses alpha of 0.25)
[scratchString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithCalibratedWhite:whenLight(1.0) alpha:0.25] range:fullRange];
[scratchString drawInRect:cellFrame];
}
#end
Please don't pick this as the answer I just implemented the above suggestions for fun and put it here because it will probably be useful to someone in the future!
https://github.com/danieljfarrell/InnerShadowTextFieldCell
Following from the advice of indragie and wil-shipley here is a subclass of NSTextFieldCell that draws the text with an inner shadow.
The header file,
// InnerShadowTextFieldCell.h
#import <Cocoa/Cocoa.h>
#interface InnerShadowTextFieldCell : NSTextFieldCell
#property (strong) NSShadow *innerShadow;
#end
Now the implementation file,
// InnerShadowTextFieldCell.m
#import "InnerShadowTextFieldCell.h"
// This class needs the NSString category -bezierWithFont: from,
// https://developer.apple.com/library/mac/samplecode/SpeedometerView/Listings/SpeedyCategories_m.html
#implementation InnerShadowTextFieldCell
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
//// Shadow Declarations
if (_innerShadow == nil) {
/* Inner shadow has not been set, override here with default shadow.
You may or may not want this behaviour. */
_innerShadow = [[NSShadow alloc] init];
[_innerShadow setShadowColor: [NSColor darkGrayColor]];
[_innerShadow setShadowOffset: NSMakeSize(0.1, 0.1)];
/* Trying to find a default shadow radius which will look good for
a label of any size, let's get a rough estimate based on the
hypotenuse of the cell frame. */
[_innerShadow setShadowBlurRadius: 0.0075 * hypot(NSWidth(cellFrame), NSHeight(cellFrame)) ];
}
/* Because we are using the -bezierWithFont: we get a slightly
different path than had we used the superclass to drawn the
text path. This means that the background colour and text
colour looks odd if we use call the superclass's,
-drawInteriorWithFrame:inView: method let's do that
drawing here. Not making the call to super might cause
problems for general use (?) but for a simple label is seems
to work OK */
[self.backgroundColor setFill];
NSRectFill(cellFrame);
NSBezierPath *bezierPath = [self.title bezierWithFont:self.font];
[self.textColor setFill];
[bezierPath fill];
/* The following is inner shadow drawing method is taken from Paint Code */
////// Bezier Inner Shadow
NSShadow *shadow = _innerShadow;
NSRect bezierBorderRect = NSInsetRect([bezierPath bounds], -shadow.shadowBlurRadius, -shadow.shadowBlurRadius);
bezierBorderRect = NSOffsetRect(bezierBorderRect, -shadow.shadowOffset.width, shadow.shadowOffset.height);
bezierBorderRect = NSInsetRect(NSUnionRect(bezierBorderRect, [bezierPath bounds]), -1, -1);
NSBezierPath* bezierNegativePath = [NSBezierPath bezierPathWithRect: bezierBorderRect];
[bezierNegativePath appendBezierPath: bezierPath];
[bezierNegativePath setWindingRule: NSEvenOddWindingRule];
[NSGraphicsContext saveGraphicsState];
{
NSShadow* shadowWithOffset = [shadow copy];
CGFloat xOffset = shadowWithOffset.shadowOffset.width + round(bezierBorderRect.size.width);
CGFloat yOffset = shadowWithOffset.shadowOffset.height;
shadowWithOffset.shadowOffset = NSMakeSize(xOffset + copysign(0.0, xOffset), yOffset + copysign(0.1, yOffset));
[shadowWithOffset set];
[[NSColor grayColor] setFill];
[bezierPath addClip];
NSAffineTransform* transform = [NSAffineTransform transform];
[transform translateXBy: -round(bezierBorderRect.size.width) yBy: 0];
[[transform transformBezierPath: bezierNegativePath] fill];
}
[NSGraphicsContext restoreGraphicsState];
}
#end
This could probably be made more robust but it seems fine for just drawing static labels.
Make sure your change the text color and text background color properties in Interface Builder otherwise you will not be able to see the shadow.
From your screenshot, that looks like text drawn with an inner shadow. Hence, the standard NSShadow method of using a blur radius of 0 won't work because that only draws the shadow under/above the text.
There are two steps to drawing text with an inner shadow.
1. Get the drawing path of the text
To be able to draw a shadow inside the text glyphs, you need to create a bezier path from the string. The Apple sample code SpeedometerView has a category that adds the method -bezierWithFont: to NSString. Run the project to see how this method is used.
2. Fill the path with an inner shadow
Drawing shadows under bezier paths is easy, but drawing a shadow inside one is not trivial. Fortunately, the NSBezierPath+MCAdditions category adds the -[NSBezierPath fillWithInnerShadow:] method to make this easy.

How do I prevent a text stroke from cutting off at the edge of a UILabel?

I'm adding a fairly wide stroke of a few pixels to text in a UILabel, and depending on the line spacing, if the very edges of the text touch the very edges of the label, the sides of the stroke can be cut off, if they go outside of the bounds of the label. How can I prevent this? Here's the code I'm using to apply the stroke (currently of 5px):
- (void) drawTextInRect: (CGRect) rect
{
UIColor *textColor = self.textColor;
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c, 5);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
self.textColor = [UIColor colorWithRed: 0.165 green: 0.635 blue: 0.843 alpha: 1.0];
[super drawTextInRect: rect];
}
Here's an example of the clipping at the side of the label, I think what needs to happen is one of the following:
That when the text splits onto multiple lines, some space is given inside the label's frame for the stroke to occupy.
Or, that the stroke is allowed to overflow the outer bounds of the label.
Yup, clipping just didn't work.
What if you create insets on your UILabel sub-class though. You'd make the frame of the label however big you need it to be, then set your insets. When you draw the text, it will use the insets to give you padding around any edge you need.
The downside is, you won't be able to judge line wrapping at a glance in IB. You'd have to take your label and subtract your insets then you'll see what it would really look line on the screen.
.h
#interface MyLabel : UILabel
#property (nonatomic) UIEdgeInsets insets;
#end
.m
#implementation MyLabel
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.insets = UIEdgeInsetsMake(0, 3, 0, 3);
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGRect actualTextContentRect = rect;
actualTextContentRect.origin.x += self.insets.left;
actualTextContentRect.origin.y += self.insets.top;
actualTextContentRect.size.width -= self.insets.right;
actualTextContentRect.size.height -= self.insets.bottom;
CGContextSetLineWidth(c, 5);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
self.textColor = [UIColor colorWithRed: 0.165 green: 0.635 blue: 0.843 alpha: 1.0];
[super drawTextInRect:actualTextContentRect];
CGContextRestoreGState(c);
self.textColor = [UIColor whiteColor];
[super drawTextInRect:actualTextContentRect];
}
Edit: Added full code for my UILabel subclass. Modified the code slightly to show both the large stroke and the the normal lettering.
You should implement sizeThatFits: on your UILabel subclass to return a slightly larger preferred size, taking the additional space required for the stroke into consideration. You can then either use the result of sizeThatFits: to calculate the label's frame correctly, or just call sizeToFit.

Scaling UITextView using contentScaleFactor property

I am trying to create a higher resolution image of a UIView, specifically UITextView.
This question and answer is exactly what I am trying to figure out:
Retain the resolution of the label after scaling in iphone
But, when I do the same, my text is still blurry:
self.view.transform = CGAffineTransformMakeScale(2.f, 2.f);
[myText setContentScaleFactor:2.f]; // myText is a subview of self.view object
I have also tried the same in the Apple sample project "UICatalog" to UILabel and it is also blurry.
I can't understand why it would work for Warrior from the other question and not for me. I would have asked there — but I can't seem to leave a comment or a question there.
Setting the contentScaleFactor and contentsScale is in fact the key, as #dbotha pointed out, however you have to walk the view and layer hierarchies separately in order to reach every internal CATiledLayer that actually does the text rendering. Adding the screen scale might also make sense.
So the correct implementation would be something like this:
- (void)updateForZoomScale:(CGFloat)zoomScale {
CGFloat screenAndZoomScale = zoomScale * [UIScreen mainScreen].scale;
// Walk the layer and view hierarchies separately. We need to reach all tiled layers.
[self applyScale:(zoomScale * [UIScreen mainScreen].scale) toView:self.textView];
[self applyScale:(zoomScale * [UIScreen mainScreen].scale) toLayer:self.textView.layer];
}
- (void)applyScale:(CGFloat)scale toView:(UIView *)view {
view.contentScaleFactor = scale;
for (UIView *subview in view.subviews) {
[self applyScale:scale toView:subview];
}
}
- (void)applyScale:(CGFloat)scale toLayer:(CALayer *)layer {
layer.contentsScale = scale;
for (CALayer *sublayer in layer.sublayers) {
[self applyScale:scale toLayer:sublayer];
}
}
UITextView has textInputView property, which "both draws the text and provides a coordinate system" (https://developer.apple.com/reference/uikit/uitextinput/1614564-textinputview)
So i'm using the following code to scale UITextView - without any font changes, without using any "CALayer" property and keeping high quality:
float screenScaleFactor = [[UIScreen mainScreen] scale];
float scale = 5.0;
textView.transform = CGAffineTransformMakeScale(scale, scale);
textView.textInputView.contentScaleFactor = screenScaleFactor * scale;
Comment the last line if you need low quality (but better performance) scaling.
Transform uses view.center as scaling center point, so adding a 'translate transform' is needed to scale around view corner.
Be sure to apply the contentScaleFactor to all subviews of the UITextView. I've just tested the following with a UITextView and found it to work:
- (void)applyScale:(CGFloat)scale toView:(UIView *)view {
view.contentScaleFactor = scale;
view.layer.contentsScale = scale;
for (UIView *subview in view.subviews) {
[self applyScale:scale toView:subview];
}
}

How to programmatically add text to a UIView

I have a UIView that I'd like to add several bits of text to. I have used a UITextView but I think that's overkill as it doesn't need to be editable. I thought about using a UILabel or a UITextField, but I don't see how you tell the superview where to position the UILabel or UITextField within itself. I want the lowest footprint object that will let me put text of a font/color/size of my choosing in my UIView where I want it. Not too much to ask, eh?
The simplest approach for you would be:
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: #"Trebuchet MS" size: 14.0f]];
[yourSuperView addSubview:yourLabel];
Building or populating Views in your code will probably require you to use CGRectMake a lot.
As its name says, it creates a rectangle that you can use to set the relative position (relative to the borders of your superview) and size of your UIView-Subclass (in this case a UILabel).
It works like this:
yourLabel.Frame = CGRectMake(x, y, width, height); //x,y,width,height are float values.
x defines the spacing between the left hand border of the superview and the beginning of the subview your about to add, same applies to y but relating to the spacing between top-border of your superview.
then width and height are self-explanatory i think.
Hope this gets you on the track.
Instead of finding a way to tell the view where to position the UILabel, you can tell the UILabel where to position itself in the view by using "center".
E.g.
myLabel.center = CGPointMake(0.0, 0.0);
Hope you'll be able to use UILabel, for me it's the basic form of a flexible non editable text.
For Swift:
let yourLabel = UILabel(frame: CGRectMake(100, 100, 100, 100))
yourLabel.textColor = UIColor.whiteColor()
yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
yoursuperview.addSubview(yourLabel)
This question is old, but for a pure UIView text option without using UILabel or UITextField (as all the other answers describe, but the question is how to do it without them), drawRect in a subclassed UIView works for me. Like so:
- (void)drawRect:(CGRect)rect{
NSString *string = #"Hello World!";
[string drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:16.0]];
}
This routine displays a text at a X-Y position
-(void)placeText:(NSString *)theText:(int)theX:(int)theY {
UILabel *textLabel;
// Set font and calculate used space
UIFont *textFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize textStringSize = [theText sizeWithFont:textFont constrainedToSize:CGSizeMake(300,50) lineBreakMode:NSLineBreakByTruncatingTail];
// Position of the text
textLabel = [[UILabel alloc] initWithFrame:CGRectMake(theX+OFFSETIMAGEX-(textStringSize.width/2), theY+OFFSETIMAGEY-(textStringSize.height/2), textStringSize.width,textStringSize.height)];
// Set text attributes
textLabel.textColor = [UIColor blackColor];
textLabel.backgroundColor = [UIColor orangeColor];
textLabel.font = textFont;
textLabel.text = theText;
// Display text
[self.view addSubview:textLabel];
}
It might be late but here is what I use:-
CGRect labelFrame = CGRectMake(120,300, 530, 100);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
//If you need to change the color
[myLabel setTextColor:[UIColor whiteColor]];
//If you need to change the system font
[myLabel setFont:[UIFont fontWithName:NULL size:23]];
//If you need alignment
[myLabel setTextAlignment:NSTextAlignmentCenter];
// The label will use an unlimited number of lines
[myLabel setNumberOfLines:0];
//Add label view to current view
[self.view addSubview:myLabel];
NSString *someString = #"Sample String, Yarp!";
myLabel.text = someString;
add a UILabel to your View. then override the View's layoutSubviews method.