アイコンフォントを Xamarin.iOS プロジェクトに組み込む
- Xamarin.iOS プロジェクトの Resources フォルダにアイコンフォントのファイル(.ttf)を追加。
- プロパティでビルドアクションを BundleResource にする。
- Info.plist をエディタで編集して下記を追加。
<key>UIAppFonts</key>
<array>
<string>使いたいアイコンフォント.ttf</string>
</array>
UILabel で使う
普通に UIFont で指定すればいい。
TextLabel.Font = UIFont.FromName(
name: "使いたいアイコンフォント",
size: fontSize);
TextLabel.Text = "アイコンの Unicode";
UIImage に変換して使う
アイコンフォントを UIImage に変換するメソッドを用意しておく。
using CoreGraphics;
using Foundation;
using UIKit;
public static class UIImageEx
{
public static UIImage FromFont(
string name,
string glyph,
float size,
UIColor color)
{
var imageSize = new CGSize(size, size);
var font = UIFont.FromName(name, size) ?? UIFont.SystemFontOfSize(size);
UIGraphics.BeginImageContextWithOptions(imageSize, false, 0f);
var attString = new NSAttributedString(
glyph,
font: font,
foregroundColor: color);
var ctx = new NSStringDrawingContext();
var boundingRect = attString.GetBoundingRect(
size: imageSize,
options: (NSStringDrawingOptions)0,
context: ctx);
var imageRect = new CGRect(
x: imageSize.Width / 2 - boundingRect.Size.Width / 2,
y: imageSize.Height / 2 - boundingRect.Size.Height / 2,
width: imageSize.Width,
height: imageSize.Height);
attString.DrawString(imageRect);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
}
ボタンのアイコンや UIImageView で使うには UIImage に変換してやる必要があるので、このメソッドを使う。
ImageView.Image = UIImageEx.FromFont(
name: "使いたいアイコンフォント",
glyph: "アイコンの Unicode",
size: 20,
color: UIColor.Gray);