我正在尝试在textView上执行子类。它不会起作用。当我将类从textView扩展到View时。有用。但我需要TextView的功能。
但我无法在onDraw()例程中执行任何drawLine或drawBitmap。但drawText()和drawColor()可以工作。我不明白为什么。
我无法找到onDraw()的任何问题。有人能告诉我,我做错了什么吗?或者TextView不允许绘制位图或线条? 下面是我的代码
package com.name.name;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;
public class RDisplay extends TextView {
Paint p;
private String mName = "";
private static Bitmap mImage = null;
Context mContext;
public RDisplay (Context context) {
super(context);
mContext = context;
initComponent();
}
public RDisplay (Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initComponent();
}
public void initComponent()
{
p = new Paint();
p.setTextSize(30);
p.setColor(Color.WHITE);
}
public void setName(String name)
{
mName = name;
String file = "f_" + name.toLowerCase();
Drawable d = mContext.getResources().getDrawable(R.drawable.image);
mImage = ((BitmapDrawable)d).getBitmap();
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
Paint paint = new Paint();
paint.setStrokeWidth(20);
paint.setColor(Color.WHITE);
// drawText() Working
canvas.drawText(mName, 0, getMeasuredHeight(), paint);
// drawLine() Not Working
canvas.drawLine(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);
if(mImage != null)
{ canvas.drawColor(Color.BLACK); //Working
canvas.drawBitmap(mImage, 10, 10, null); // Not working
}
}
void setFont(String fontName)
{
Typeface font = Typeface.createFromAsset(mContext.getAssets(), fontName);
setTypeface(font);
}
}
答案 0 :(得分:0)
看起来您实际上从未实际调用setName(String)
,mImage
为空。另外,我很好的做法不在绘制中创建绘画。在初始化方法中创建它们并根据需要进行设置。