Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a label using NSTextField is blurry

I'm trying to create a label programmatically using NSTextField, but it comes out blurry: screenshot

This is my code so far:

NSTextfield *textfield = [[NSTextField alloc] initWithFrame:NSMakeRect(5,5,150,20)];
[texField setStringValue:@"some text here"];
[textField setEditable:NO];
[textField setSelectable:NO];
[textField setBordered:NO]
[textField setDrawsBackground:NO]

I've traced the problem down to the setDrawsBackground line. I've also tried using [textField setBackgroundColor:[NSColor clearColor] as well, but no luck.

By the way, I've adding to a textField to the subview of a view that is a subview of a scrollview. I've also playing with isOpaque on all the view levels, but no luck there again.

Any help is greatly appreciated.

like image 843
IEb Avatar asked Oct 12 '10 18:10

IEb


4 Answers

If you have no background (including clear) and your text is a subview of any layer-backed superview (you've turned on "wants layer" in code or in IB to allow animations/transitions), you'll get blurry text. You have to choose either no layer backed view or a label with a solid background color.

like image 146
Joshua Nozzi Avatar answered Nov 20 '22 03:11

Joshua Nozzi


I had the same problem, but I have solved it by:

textfield.canDrawSubviewsIntoLayer = true
like image 43
Pavel Zverina Avatar answered Nov 20 '22 03:11

Pavel Zverina


Make sure you're setting the frame of your NSTextField to something with all integer values.

Use roundf() if necessary.

I was getting a blurry NSTextField, and neither adding a solid background nor removing Core Animation layers from my view hierarchy were options for me. I noticed I was setting the frame of this text field to something with a Y value of 4.5, so the following changes fixed the issue for me:

Blurry label:

_label.frame = NSOffsetRect(_labelFrame,
                            -0.5 * (someRect.size.width + someConstant),
                            0.0);

No blur:

_label.frame = NSOffsetRect(_labelFrame,
                            roundf(-0.5 * (someRect.size.width + someConstant)),
                            0.0);

(In the above examples, _labelFrame and someRect are NSRects, and someConstant is a CGFloat. As you can see, the calculation I was doing in the second line of the first example was passing a non-integer value to NSOffsetRect).

like image 45
T Blank Avatar answered Nov 20 '22 03:11

T Blank


Since this was my first time subclassing NSView, I had put the above code in the drawRect method instead of the initWithFrame method. I did this because I was following one of the sample applications from Apple's Dev site.

This was also causing my CPU usage to spike when I was scrolling

like image 1
IEb Avatar answered Nov 20 '22 02:11

IEb