我需要能够在CGContext中绘制自定义字体,但是当我更改我选择字体的方式时,字体不会显示。
//Works
protected void DrawCenteredTextAtPoint(CGContext context, float centerX, float y, string text, int textHeight)
{
context.SelectFont("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman);
context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
context.ShowTextAtPoint(centerX, y, text, text.Length);
context.SetTextDrawingMode(CGTextDrawingMode.Fill);
context.ShowTextAtPoint(centerX - (context.TextPosition.X - centerX)/2, y, text, text.Length);
}
//Does not work
protected void DrawCenteredTextAtPoint(CGContext context, float centerX, float y, string text, int textHeight)
{
var fontPath = NSBundle.MainBundle.PathForResource("COOPBL", "ttf", "fonts", "");
var provider = new CGDataProvider(fontPath);
var font = CGFont.CreateFromProvider(provider);
context.SetFont(font);
context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
context.ShowTextAtPoint(centerX, y, text, text.Length);
context.SetTextDrawingMode(CGTextDrawingMode.Fill);
context.ShowTextAtPoint(centerX - (context.TextPosition.X - centerX)/2, y, text, text.Length);
}
答案 0 :(得分:0)
有效:
protected void DrawCenteredTextAtPoint(CGContext context, float centerX, float y, string text, int textHeight)
{
// var fontPath = NSBundle.MainBundle.PathForResource("COOPBL", "ttf", "fonts", "");
// var provider = new CGDataProvider(fontPath);
// var font = CGFont.CreateFromProvider(provider);
//context.SelectFont("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman);
//var cgFont = CGFont.CreateWithFontName("Cooper Black");
//context.SetFont(cgFont);
context.SelectFont("Cooper Black", textHeight, CGTextEncoding.MacRoman);
context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
context.ShowTextAtPoint(centerX, y, text, text.Length);
context.SetTextDrawingMode(CGTextDrawingMode.Fill);
context.ShowTextAtPoint(centerX - (context.TextPosition.X - centerX)/2, y, text, text.Length);
}
我如何使用
...
public class CustomView: UIView
{
public CustomView ()
{
}
public override void Draw (System.Drawing.RectangleF rect)
{
base.Draw (rect);
var context = UIGraphics.GetCurrentContext();
DrawCenteredTextAtPoint(UIGraphics.GetCurrentContext(), 50, 10, "adsasdasd", 20);
}
...
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
v = new CustomView();
v.BackgroundColor = UIColor.Red;
View.AddSubview(v);
v.Frame = new RectangleF(0, 100, 320, 100);
...
使用Cooper Black
font:
请注意,您应该正确地向项目添加字体:
Content
; Build Action
备注:http://fastchicken.co.nz/2012/09/07/using-fonts-in-a-monotouch-app/。