改变Android Canvas Path颜色的正确方法

时间:2014-01-22 04:34:08

标签: android colors android-canvas

我目前正在使用fingerpaint

处理画布绘图模块

假设绘图笔的默认颜色为黑色。当通过HSVColor对话框选择颜色然后触摸屏幕时,所有先前绘制的颜色将更改为当前颜色而不是之前的路径黑色,最新的storke是已选择任何颜色。您能否告诉我修改onDraw Canvas或ACTION_DOWN的指导原则,以查看之前的笔触颜色是否未被覆盖

以下是我的代码

import java.io.File;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;

import com.galden.drawsth.asynctask.UploadImage;
import com.galden.drawsth.util.HSVColorPickerDialog;
import com.galden.drawsth.util.HSVColorPickerDialog.OnColorSelectedListener;
import com.galden.drawsth.util.SystemUtils;


import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    private String sign;
    LinearLayout mContent;
    signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    File mypath;
    LinearLayout signlayout;
    public static final int BUFFER_SIZE = 1024 * 8;

    private ArrayList<Path> undonePaths = new ArrayList<Path>();
    private ArrayList<Path> paths = new ArrayList<Path>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        signlayout = (LinearLayout) findViewById(R.id.linearLayout1);
        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new signature(getApplicationContext(), null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        mView = mContent;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if( keyCode==KeyEvent.KEYCODE_BACK) 
        {
            System.out.println("BACK");
            return false;
        }
        else{
            return super.onKeyDown(keyCode, event);     
        }
    }


    public class signature extends View {
        private static final float STROKE_WIDTH = 10f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Canvas mCanvas;
        private float mX;
        private float mY;
        private Bitmap bitmap; // drawing area for display or saving
        private Path mPath; 
        private ArrayList<Path> paths = new ArrayList<Path>();
        private ArrayList<Path> undonePaths = new ArrayList<Path>();
        private static final float TOUCH_TOLERANCE = 4;    
        private Paint paint;
        private final RectF dirtyRect = new RectF();

        public signature(Context context, AttributeSet attrs) {
            super(context, attrs);

            initialisePen(Color.BLACK); 
        }



        private void initialisePen(int color) {
            // TODO Auto-generated method stub
            paint = new Paint();
            paint.setDither(true);
            paint.setAntiAlias(true);
            paint.setColor(color);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH); 
            paint.setStrokeCap(Paint.Cap.ROUND);
            mCanvas = new Canvas();
            mPath = new Path();


        }



        public void save(View v) {

            if (mBitmap == null) {
                mBitmap = Bitmap.createBitmap(mContent.getWidth(),  mContent.getHeight(), Bitmap.Config.RGB_565);
            }



            Canvas canvas = new Canvas(mBitmap);
            try {

                v.draw(canvas);
                String path = Environment.getExternalStorageDirectory().getAbsolutePath()  + File.separator + "CanvasTest";
                File dir = new File(path);
                if(!dir.exists()){
                    dir.mkdir();
                }

                Calendar c = Calendar.getInstance();

                String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND);
                String name = date + ".jpg";
                File file = new File(dir.getAbsolutePath() + File.separator + name );
                file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
                mBitmap.compress(CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
                fos.close();
                Toast.makeText(getApplicationContext(), file.getName() + " is generated", Toast.LENGTH_SHORT).show();
                mypath = file;

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public void clear() {


            if (paths.size()>0) 
            { 
                paths.removeAll(paths);
                invalidate();
            }   
            invalidate();
        }

        public void colorChanged(int color) {
            initialisePen(color);   
        }


        @Override
        protected void onDraw(Canvas canvas) {            
            for (Path p : paths) {
                canvas.drawPath(p, paint);
            }
            canvas.drawPath(mPath, paint);
        }

        public boolean onTouchEvent(MotionEvent event) 
        {            
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction())
            {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
            }
            return true;
        }


        private void touch_start(float x, float y) 
        {
            undonePaths.clear();
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }

        private void touch_move(float x, float y) 
        {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) 
            {
                mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }  

        private void touch_up() 
        {
            mPath.lineTo(mX, mY);      
            mCanvas.drawPath(mPath, paint);// commit the path to our offscreen  
            paths.add(mPath);
            mPath = new Path(); 
        }


        public void onClickUndo() 
        { 
            if (paths.size()>0) 
            { 
                undonePaths.add(paths.remove(paths.size()-1));
                invalidate();
            }      
            else Toast.makeText(getContext(), "nothing more to undo", Toast.LENGTH_SHORT).show();  
        }


    }



    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putString("signCanvas", sign);
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_clear:
            SystemUtils.toast(this, "Clear");
            mSignature.clear();
            //mGetSign.setEnabled(false);
            return true;
        case R.id.action_exit:
            SystemUtils.toast(this, "Exit");
            finish();
            return true;
        case R.id.action_undo:
            SystemUtils.toast(this, "Undo");
            mSignature.onClickUndo();
            return true;

        case R.id.action_save:
            SystemUtils.toast(this, "Save");
            mView.setDrawingCacheEnabled(true);
            mSignature.save(mView);
            return true;
        case R.id.action_upload:
            SystemUtils.toast(this, "Upload");
            mView.setDrawingCacheEnabled(true);
            mSignature.save(mView);
            new UploadImage(MainActivity.this).execute(mypath);
            return true;        
        case R.id.action_select:
            HSVColorPickerDialog cpd = new HSVColorPickerDialog( MainActivity.this, 0xFF4488CC, new OnColorSelectedListener() {
                @Override
                public void colorSelected(Integer color) {
                    // Do something with the selected color
                    mSignature.colorChanged(color);                             
                }
            });
            cpd.setTitle( "Pick a color" );
            cpd.setNoColorButton( R.string.no_color );
            cpd.show();
            return true;                
            /*case R.id.action_setting:
            SystemUtils.toast(this, "Setting");
            return true;*/
        default:
            return super.onOptionsItemSelected(item);
        }
    }


}

0 个答案:

没有答案