android 基础一

public class CanvasActivity extends AppCompatActivity {

    String TAG="test2";
    ImageView imageView;
    Canvas canvas;
    Paint paint;
    int startX=0;
    int startY=0;
    Bitmap bitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        imageView=(ImageView)findViewById(R.id.imageView);
        init();
    }
    private void init() {
        //创建空白画布
        bitmap= Bitmap.createBitmap(getWindowManager().getDefaultDisplay().getWidth(),getWindowManager().getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_4444);
        canvas=new Canvas(bitmap);
        //设置画布背景颜色
        canvas.drawRGB(0xAA,0xAA,0xAA);
        paint=new Paint();
        //设置画笔的宽度
        paint.setStrokeWidth(10);
        //设置画笔的颜色
        paint.setColor(0xFFFF0000);
        imageView.setImageBitmap(bitmap);
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    Log.e(TAG,"ACTION_DOWN0");
                    startX=(int)(event.getX());
                    startY=(int)(event.getY());
                }else if(event.getAction()==MotionEvent.ACTION_MOVE){
                    Log.e(TAG,"ACTION_MOVE  startX="+startX +"  startY="+startY +"   v.getX()="+(int)event.getX() +"   v.getY()="+(int)event.getY());
                    canvas.drawLine(startX,startY,(int)event.getX(),(int)event.getY(),paint);
                    startX=(int)(event.getX());
                    startY=(int)(event.getY());
                    imageView.setImageBitmap(bitmap);
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    Log.e(TAG,"ACTION_UP");

                    try {
                        String path = Environment.getExternalStorageDirectory() + File.separator + "test.png";
                        FileOutputStream fileOutputStream = new FileOutputStream(path);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);  //保存图片
                        canvas.drawRGB(0xAA, 0xAA, 0xAA);//清除画板的数据
                        imageView.setImageBitmap(bitmap);
                    }catch (Exception ex){

                    }
                }
                return true;
            }
        });


    }

  

android 基础一 <Canvas>

上一篇:移动端布局方案,简单高效,完美适配各种机型


下一篇:javascript继承—继承的实现原理(1)