我可以用“png”文件创建图像。
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Operation"
image:[UIImage imageNamed:@"plus.png"] tag:0 ];
但我想使用 unicode 图像 (721) 或字符 val,即:
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Operation"
image: {unicode: 721 }];
我该怎么做?谢谢
最佳答案
我创建了一个小辅助方法,它从通常包含单个 Unicode 字符的 NSString
创建一个小图像。
+ (UIImage *)characterImage:(NSString *)ch {
UIFont *font = [UIFont boldSystemFontOfSize:12];
CGSize chsize = [ch sizeWithAttributes:@{ NSFontAttributeName : font }];
CGSize imgsize = CGSizeMake(16, 16);
UIGraphicsBeginImageContextWithOptions(imgsize, NO, [UIScreen mainScreen].scale);
CGRect rect = CGRectMake((imgsize.width - chsize.width) / 2.0, (imgsize.height - chsize.height) / 2.0, chsize.width, chsize.height);
NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc] init];
pStyle.alignment = NSTextAlignmentCenter;
pStyle.lineBreakMode = NSLineBreakByClipping;
NSDictionary *attrs = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : pStyle };
[ch drawInRect:rect withAttributes:attrs];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
调整字体大小和图像大小以满足您的需要。
然后你可以这样做:
NSString *tabChar = @"✚"; // Unicode U+271A
UIImage *tabImg = [SomeHelperClass characterImage:tabChar];
根据添加方法的位置调整对 characterImage:
的调用。
关于ios - 如何使 UITabBarItem 成为来自 unicode 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34733001/