实现比较简单.
public class UIButton extends Button
{
private int COVER_ALPHA = 48;
private Paint mPressedPaint;
private int mPressedColor;
private int WIDTH;
private int HEIGHT;
private int mRadius;
public UIButton(Context context) {
super(context);
init(context);
}
protected void init(Context context) {
//mRadius = 10;设置圆角更好看, 但是要保证Button也是圆角
mRadius = 0;
mPressedColor = Color.GRAY;
mPressedPaint = new Paint();
mPressedPaint.setStyle(Paint.Style.FILL);
mPressedPaint.setColor(mPressedColor);
mPressedPaint.setAlpha(0);
mPressedPaint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
WIDTH = w;
HEIGHT = h;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF rectF = new RectF();
rectF.set(0, 0, WIDTH, HEIGHT);
canvas.drawRoundRect(rectF, mRadius, mRadius, mPressedPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPressedPaint.setAlpha(COVER_ALPHA);
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mPressedPaint.setAlpha(0);
invalidate();
break;
}
return super.onTouchEvent(event);
}
}
参考https://github.com/drakeet/AndroidUIView
这是一个很好的标准的自定义控件的例子.
学习到的注意的地方:
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLUE);
canvas.drawLine(0, 0, 100, 1000, paint);
canvas.drawText("test", 0,200, paint); //注意text的绘制是从下向上! 从t的下方!! 如果写成0,0就会看不到!!
view.draw(canvas);