gpt4 book ai didi

java - 在自定义 Drawable 类中获取 Context

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:24 24 4
gpt4 key购买 nike

我试图创建一个自定义类以将文本实现为可绘制的,但我无法将 Typeface 设置为 Paint。下面是自定义类(即 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;
}
}

最佳答案

I am not able to get getContext().getAssets() in this class.

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


public class TextDrawable extends Drawable {
...

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

关于java - 在自定义 Drawable 类中获取 Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47411392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com