3

我试图创建一个自定义类以将文本实现为可绘制但我无法设置TypefacePaint. 下面是自定义类(即TextDrawable)的代码实现。

这里我想获取Application的上下文来调用方法getAssets(),但是这里我无法调用方法getContext()

public class TextDrawable extends Drawable {
    private final String text;
    private final Paint paint;

    public TextDrawable(String text) {
        this.text = text;
        this.paint = new Paint();
        paint.setColor(Color.GRAY);
        paint.setTextSize(35f);
        //paint.setTypeface(Typeface.createFromAsset(**getContext().getAssets()**, "fonts/Montserrat-Regular.otf"));
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.RIGHT);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawText(text, 0, 10, paint);
    }

    @Override
    public void setAlpha(int alpha) {
        paint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        paint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}
4

2 回答 2

3

我无法在此类中获取 getContext().getAssets()。

您必须将Context对象作为参数传递给类的构造函数:


    public class TextDrawable extends Drawable {
        ...

        public TextDrawable(Context context, String text) {
            paint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.otf"));
            ...
        }
        ...
    }

于 2017-11-21T11:54:32.657 回答
3

可绘制对象没有上下文。所以正如@azizbekian 和@Mike M 所建议的,你有两个选择。

在构造函数中传递上下文

public TextDrawable(Context context, String text) {
    paint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.otf"));
    ...
}

请注意,每次使用此 Drawable 时,这种方法都会创建一个新的 Typeface 实例,这通常是一种不好的做法,也会直接影响性能。

在构造函数中传递字体

public TextDrawable(String text, Typeface typeface) {
    paint.setTypeface(typeface);
    ...
}

这种方法更好,因为您可以对与此 Drawable 相关或不相关的多个对象使用单个 Typeface 实例。

扩展后一种方法,您可以创建一个静态 TypefaceProvider,如下所示。这确保您始终只有一个字体实例。

字体提供者

public class TypefaceProvider
{
    private static Map<String, Typeface> TYPEFACE_MAP = new HashMap<>();

    public static Typeface getTypeFaceForFont(Context context, String fontFile)
    {
        if (fontFile.length() <= 0) throw new InvalidParameterException("Font filename cannot be null or empty");
        if (!TYPEFACE_MAP.containsKey(fontFile))
        {
            try
            {
                Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"+fontFile);
                TYPEFACE_MAP.put(fontFile, typeface);
            }
            catch (Exception e)
            {
                throw new RuntimeException(String.format("Font file not found.\nMake sure that %s exists under \"assets/fonts/\" folder", fontFile));
            }
        }

        return TYPEFACE_MAP.get(fontFile);
    }
}
于 2017-11-21T12:52:27.317 回答