1

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

这是我现在拥有的

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;
    }
}
4

1 回答 1

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()方法的主体,以便它使用CanvasfromonDraw()并将其设置Bitmap为您创建的方法。

于 2013-01-22T10:45:25.420 回答