0

我需要能够在 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);
}
4

1 回答 1

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字体看起来如何:

在此处输入图像描述

请注意,您应该正确地将字体添加到项目中:

  • 将字体文件引用添加到 cproj-file;
  • 将字体文件标记ContentBuild Action;
  • 添加对Info.plist 文件的字体文件引用。

注: http: //fastchicken.co.nz/2012/09/07/using-fonts-in-a-monotouch-app/

于 2013-04-02T06:01:09.467 回答