使用onDraw自定义背景的EditText

时间:2013-01-22 10:35:15

标签: android android-edittext

我正在尝试使用自定义背景的自定义EditText,无法使用可绘制的XML进行绘制

这就是我现在所拥有的

public class EMEditText extends EditText {
    private Bitmap framedBitmap;

    public EMEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(framedBitmap == null) {
            createDrawable(getWidth(), getHeight());
        }

        Paint paint = new Paint();
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // canvas.drawBitmap(framedBitmap, 0, 0, paint);
    }

    private void createDrawable(int width, int height) {
        // create a new bitmap of given size
        Bitmap start = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(start);

        RectF outerRect = new RectF(0, 0, width, height);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        // paint.setStrokeWidth(1);
        // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
        canvas.drawRoundRect(outerRect, height / 2, height / 2, paint);
        framedBitmap = start;
    }
}

1 个答案:

答案 0 :(得分:2)

您的代码中可能存在的错误是,您在Canvas方法中创建了自己的createDrawable()对象,但onDraw()方法为您提供了您应该使用的Canvas权利为您的图纸。

所以您可能希望将createDrawable(int width, int height)方法更改为createDrawable(int width, int height, Canvas c)。您的代码应如下所示:

@Override
protected void onDraw(Canvas canvas) {
    if(framedBitmap == null) {
        createDrawable(getWidth(), getHeight(), canvas);
    }

    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    // canvas.drawBitmap(framedBitmap, 0, 0, paint);
}

private void createDrawable(int width, int height, Canvas c) {
    // create a new bitmap of given size
    Bitmap start = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    c.setBitmap(start);

    RectF outerRect = new RectF(0, 0, width, height);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.WHITE);
    // paint.setStrokeWidth(1);
    // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
    c.drawRoundRect(outerRect, height / 2, height / 2, paint);
    framedBitmap = start;
}

正如您所看到的,我还更改了createDrawable()方法的正文,以便它使用Canvas中的onDraw()并将其Bitmap设置为您创建的{{1}}