在Android中创建画布上的按钮

时间:2016-05-21 17:27:09

标签: android button canvas bitmap draw

我遇到了问题,我不知道如何在画布上创建按钮。下面这段代码我写的是在图片上画一条线。然后我想在那张照片上添加一些按钮。希望你们能帮助我。

public class DrawShape extends Activity implements View.OnTouchListener {
ImageView imagTest;
Bitmap bitmap;
Canvas canvas;
Paint paint;
Button abc;
float downX, downY, moveX, moveY, upX, upY = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawshape);

    imagTest = (ImageView) findViewById(R.id.imgTest);//Add image 

    Display display = getWindowManager().getDefaultDisplay();
    int dw = display.getWidth();
    int dh = display.getHeight();

    Bitmap loadedBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);//load image onto bitmap
    Bitmap scaledloadedBitmap = Bitmap.createScaledBitmap(loadedBitmap, dw, dh, false);
    Bitmap drawableBitmap = scaledloadedBitmap.copy(Bitmap.Config.ARGB_8888, true);
    Matrix matrix = new Matrix();
    imagTest.setScaleType(ImageView.ScaleType.MATRIX);
    matrix.postRotate(90);

    canvas = new Canvas(drawableBitmap);
    paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setShadowLayer(5, 2, 2, Color.BLUE);
    paint.setStrokeWidth(10);
    imagTest.setImageBitmap(drawableBitmap);
    imagTest.setOnTouchListener(this);


}
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downX = event.getX();
            downY = event.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            moveX = event.getX();
            moveY = event.getY();

            break;
        case MotionEvent.ACTION_UP:
            upX = event.getX();
            upY = event.getY();
            canvas.drawLine(downX, downY, upX, upY, paint);//Handle when touch up
            imagTest.invalidate();
            break;
    }
    return true;
}
}

2 个答案:

答案 0 :(得分:1)

您无法在画布上放置按钮。您可以将画布放入新图层,然后使用画布将按钮添加到图层下的相关图层中。

答案 1 :(得分:0)

您需要创建一个自定义视图类,该类扩展View类=并覆盖其Button方法,如下所示:

onDraw()

public class MyButtonClass extends Button { public MyButtonClass(Context context) { super(context); // Here you can set a default parameters for this View, e.g.: this.setText("My Green Button..."); } @Override protected void onDraw(Canvas canvas) { // Here you need to declare what paint you canvas, e.g.: canvas.drawColor(Color.GREEN); // Set color canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.my_button), 0f, 0f, null); // Set drawable // .......... set others super.onDraw(canvas); } } 方法中,您需要编写下一个:

onCreate()