I have a custom font with some symbols and I can set the text to a label in a table view, getting the symbol correctly, as follows:
cell.icono.textColor=[UIColor purpleColor];
[cell.icono setFont:[UIFont fontWithName:#"icomoon" size:17]];
const char *icon = "\ue904";
[cell.icono setText:[NSString stringWithUTF8String: icon]];
Now, I am storing in my database the symbols (as string) \ue904, \ue90b, etc, and I get them correctly, I see them in the console without problems, but when I do the following I do not see the symbol, only the string "\ue904"
cell.icono.textColor=[UIColor purpleColor];
[cell.icono setFont:[UIFont fontWithName:#"icomoon" size:17]];
const char *icon = [gridprinc.icono UTF8String];
NSLog(#"%s", icon);
[cell.icono setText:[NSString stringWithUTF8String: icon]];
In the same way, if I do the following, everything works fine
cell.icono.textColor=[UIColor purpleColor];
[cell.icono setFont:[UIFont fontWithName:#"icomoon" size:17]];
NSString *icon = #"\ue907";
[cell.icono setText:icon];
But when getting the string from CoreData, the label doesn't show the symbol, but the console correctly shows the string:
cell.icono.textColor=[UIColor purpleColor];
[cell.icono setFont:[UIFont fontWithName:#"icomoon" size:17]];
NSString *icon = gridprinc.icono;
[cell.icono setText:icon];
Related
I have a chat table (correspondence)
The user text is in UITextView
Problem in that on iPhone 4 if they settle down to enter 2 characters here so
And shall be so
The text is created as follows
-(NSAttributedString *)chatStringsMy:(NSString *)string
{
NSRange rangeBold = [string rangeOfString:string];
NSDictionary *dictBoldText = #{NSFontAttributeName : [UIFont fontWithName:#"Arial" size:14.0],
NSForegroundColorAttributeName : [UIColor whiteColor]
};
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:string];
[mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];
return mutAttrTextViewString;
}
On other iPHone models everything is normal.
How to solve this problem on iPhone 4?
I'm trying to produce a set of custom page numbers. The current page number will be displayed. The others will simply be open circles.
Using the code below, I'm getting the desired results - except, with the new text attributes in iOS7, I cannot figure out how to center the number.
Any help will be appreciated.
Original iOS6 code:
[pageNumber drawInRect:CGRectMake(x,(self.frame.size.height-_currentPageDiameter)/2-1,_currentPageDiameter,_currentPageDiameter) withFont:[UIFont systemFontOfSize:_currentPageDiameter-2] lineBreakMode:UILineBreakModeCharacterWrap alignment:NSTextAlignmentCenter];
My iOS7 code:
NSString *pageNumber = [NSString stringWithFormat:#"%i", i+1];
CGContextSetFillColorWithColor(myContext, [[UIColor whiteColor] CGColor]);
UIFont* font = [UIFont systemFontOfSize:_currentPageDiameter-2];
NSDictionary *attrs = #{ NSForegroundColorAttributeName : [UIColor whiteColor],
NSFontAttributeName : font,
NSTextEffectAttributeName : NSTextEffectLetterpressStyle};
CGRect r = CGRectMake(x,(self.frame.size.height-_currentPageDiameter)/2-1,_currentPageDiameter,_currentPageDiameter);
[pageNumber drawInRect:r withAttributes:attrs];
The property you're missing for center alignment is defined the following way. I also added the line break mode you had defined on the iOS6 code:
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentCenter;
paragrapStyle.lineBreakMode = NSLineBreakByCharWrapping;
You just place them in the attributes dictionary under the key:
NSArray *attrs = #{
NSParagraphStyleAttributeName : paragraphStyle,
...
};
I've been able to adapt some code found on SO to produce an animated GIF from the "screenshots" of my view, but the results are unpredictable. GIF frames are sometimes full images, full frames ("replace" mode, as GIMP marks it), other times are just a "diff" from previous layer ("combine" mode).
From what I've seen, when there are fewer and/or smaller frames involved, the CG writes the GIF in "combine" mode, but failing to get the colors right. Actually, the moving parts are colored correctly, the background is wrong.
When CG saves the GIF as full frames, the colors are ok. The file size is larger, but hey, obviously you cannot have the best of both worlds. :)
Is there a way to either:
a) force CG to create "full frames" when saving the GIF
b) fix the colors (color table?)
What I do is (ARC mode):
capture the visible part of the view with
[[scrollView contentView] dataWithPDFInsideRect:[[scrollView contentView] visibleRect]];
convert and resize it to NSImageBitmapRep of PNG type
-(NSMutableDictionary*) pngImageProps:(int)quality {
NSMutableDictionary *pngImageProps;
pngImageProps = [[NSMutableDictionary alloc] init];
[pngImageProps setValue:[NSNumber numberWithBool:NO] forKey:NSImageInterlaced];
double compressionF = 1;
[pngImageProps setValue:[NSNumber numberWithFloat:compressionF] forKey:NSImageCompressionFactor];
return pngImageProps;
}
-(NSData*) resizeImageToData:(NSData*)data toDimX:(int)xdim andDimY:(int)ydim withQuality:(int)quality{
NSImage *image = [[NSImage alloc] initWithData:data];
NSRect inRect = NSZeroRect;
inRect.size = [image size];
NSRect outRect = NSMakeRect(0, 0, xdim, ydim);
NSImage *outImage = [[NSImage alloc] initWithSize:outRect.size];
[outImage lockFocus];
[image drawInRect:outRect fromRect:inRect operation:NSCompositeCopy fraction:1];
NSBitmapImageRep* bitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:outRect];
[outImage unlockFocus];
NSMutableDictionary *imageProps = [self pngImageProps:quality];
NSData* imageData = [bitmapRep representationUsingType:NSPNGFileType properties:imageProps];
return [imageData copy];
}
get the array of BitmapReps and create the GIF
-(CGImageRef) pngRepDataToCgImageRef:(NSData*)data {
CFDataRef imgData = (__bridge CFDataRef)data;
CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData (imgData);
CGImageRef image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
return image;
}
////////// create GIF from
NSArray *images; // holds all BitmapReps
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:pot],
kUTTypeGIF,
allImages,
NULL);
// set frame delay
NSDictionary *frameProperties = [NSDictionary
dictionaryWithObject:[NSDictionary
dictionaryWithObject:[NSNumber numberWithFloat:0.2f]
forKey:(NSString *) kCGImagePropertyGIFDelayTime]
forKey:(NSString *) kCGImagePropertyGIFDictionary];
// set gif color properties
NSMutableDictionary *gifPropsDict = [[NSMutableDictionary alloc] init];
[gifPropsDict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];
[gifPropsDict setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
// set gif loop
NSDictionary *gifProperties = [NSDictionary
dictionaryWithObject:gifPropsDict
forKey:(NSString *) kCGImagePropertyGIFDictionary];
// loop through frames and add them to GIF
for (int i=0; i < [images count]; i++) {
NSData *imageData = [images objectAtIndex:i];
CGImageRef imageRef = [self pngRepDataToCgImageRef:imageData];
CGImageDestinationAddImage(destination, imageRef, (__bridge CFDictionaryRef) (frameProperties));
}
// save the GIF
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)(gifProperties));
CGImageDestinationFinalize(destination);
CFRelease(destination);
I've checked the ImageBitmapReps, when saved as PNG individually, they are just fine.
As I understood, the color tables should be handled by CG or am I responsible to produce the dithered colors? How to do that?
Even when doing the same animation repeatedly, the GIFs produced may vary.
This is a single BitmapRep
(source: andraz.eu)
And this is the GIF with the invalid colors ("combine" mode)
(source: andraz.eu)
I read your code. Please double check the "allImages" while you are creating the CGImageDestinationRef, and the "[images count]".
the follow test code works fine:
NSDictionary *prep = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.2f] forKey:(NSString *) kCGImagePropertyGIFDelayTime] forKey:(NSString *) kCGImagePropertyGIFDictionary];
CGImageDestinationRef dst = CGImageDestinationCreateWithURL((__bridge CFURLRef)(fileURL), kUTTypeGIF, [filesArray count], nil);
for (int i=0;i<[filesArray count];i++)
{
//load anImage from array
...
CGImageRef imageRef=[anImage CGImageForProposedRect:nil context:nil hints:nil];
CGImageDestinationAddImage(dst, imageRef,(__bridge CFDictionaryRef)(prep));
}
bool fileSave = CGImageDestinationFinalize(dst);
CFRelease(dst);
I am trying to put a Attributed string inside a NSTextField, which itself is inside an NSAlert
Here is my code:
NSTextField *label1 = [[NSTextField alloc]initWithFrame:NSMakeRect(0, 23, 50, 20)];
[label1 setEditable:FALSE];
[label1 setAllowsEditingTextAttributes:TRUE];
[label1 setBezeled:FALSE];
label1.backgroundColor = [NSColor clearColor];
NSString *login = #"Username";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:login];
NSString *boldFontName = [[NSFont boldSystemFontOfSize:12] fontName];
[attrString beginEditing];
NSRange ran = NSMakeRange(0, 8);
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:ran];
[attrString endEditing];
NSLog(#"%#",attrString);
[label1 setAttributedStringValue:attrString];
[alert setAccessoryView:label1];
[alert runModal];
However, as soon as [alert runModal] is called, my app crashes
"[__NSCFConstantString pointSize]: unrecognized selector sent to instance 0x7fff74035bb0"
I'm not sure why this is happening. It appears that it is related to the string, because as soon as i remove [alert setAccessoryView:label1] or give label1 a standard nsstring it works fine. Please help!
You have done right. But you did a small mistake. You have passed NSString as an attribute for NSFontAttributeName but it expects NSFont.
Try this.
NSFont *boldFontName = [NSFont boldSystemFontOfSize:12];
[attrString beginEditing];
NSRange ran = NSMakeRange(0, 8);
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:ran];
The above answer is absolutely correct. I had a same crash which used to crash in iOS 7.0.3 & 7.0.4 only, and works perfectly in all other versions. After so much investigation, I came to know that #"HelveticaNeue-Italic" is not available in iOS 7.0.3 & 7.0.4 versions, so that I used to get above crash in those versions.
I have fixed the issue with below code :
self.headerFont = [UIFont fontWithName:#"HelveticaNeue-Italic" size:16.0f];
if (self.headerFont == nil) {
self.headerFont = [UIFont fontWithName:#"HelveticaNeue" size:16.0f];
}
I am trying to get the width of an NSString (ex. NSString *myString = #"hello"). Is there a way to do this?
Thanks.
Here's a relatively simple approach. Just create an NSAttributedString with the appropriate font and ask for its size:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}
UIFont * font = [UIFont systemFontOfSize:15];
CGSize stringSize = [aString sizeWithFont:font];
CGFloat width = stringSize.width;
Using the UILabel's attributed string:
- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{
UILabel *label = [[UILabel alloc] init];
label.text = string;
label.font = font;
return label.attributedText.size;
}
Send the string a sizeWithAttributes: message, passing a dictionary containing the attributes with which you want to measure the string.
i dont know if you are suppose to use this in cocoa touch. if it is, then:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}
wont work.
in cocoa touch, you gotta add coretext framework and import the header
and write your code like this:
UIFont *font = [UIFont fontWithName:#"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE];
// NSLog(#"%#", NSFontAttributeName);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString *)kCTFontAttributeName, nil];
but, GEE!!!!!
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes];
[as size].width;
there's no size this method in NSMutableAttributedString!
finally, this would work
[self.caption sizeWithFont:font].width
as for ios 7 and up this is the correct way:
NSString * buttonTitle = #"demo title";
CGSize stringSize = [buttonTitle sizeWithAttributes:#{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
This works with iOS 14.5
Objective-C
Define attributes:
NSDictionary *attributes = #{
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:25],
NSStrokeWidthAttributeName: #(0),
NSStrokeColorAttributeName: [UIColor blackColor]
};
Get width and height:
- (CGFloat)widthOfString:(NSString *)string {
CGSize stringSize = [string sizeWithAttributes:attributes];
return stringSize.width;
}
- (CGFloat)heightOfString:(NSString *)string {
CGSize stringSize = [string sizeWithAttributes:attributes];
return stringSize.height;
}
Sorry my question was not detailed enough and is not exactly what I'm trying to do. I am using a text storage, layout manager and a text container. The solution is to use the layout manager to determine the rectangle that bounds the rect. Here is the code.
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:#"hello"];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] init];
[layoutManager addTextContainer:textContainer];
[textContainer release];
[textStorage addLayoutManager:layoutManager];
[layoutManager release];
//Figure out the bounding rectangle
NSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];
UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:
CGSize titleSize = [title sizeWithFont:titleFont
constrainedToSize:contentCellSize
lineBreakMode:UILineBreakModeWordWrap];
Here's Stephen's solution in Clozure Common Lisp, when using the Objective C bridge. I came across this post when searching for a solution, and I just rewrote Stephen's version which worked fine for me. Others using Clozure might find this helpful:
(defun string-width (str font)
(let* ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
font #$NSFontAttributeName
ccl:+null-ptr+))
(attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string)
(ccl::%make-nsstring str)
dict))
(size (#/size attr)))
(ns:ns-size-width size)))
This will work. You can try it.
NSDictionary *attrDict = #{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
lblDeliveryDateWidth = stringBoundingBox.width;
Just in case you are wondering how to check a label size, you should use the UIFont, instead of the NSFont (not even sure if exists)