Android - How to draw with different styles?

0

Good morning, I'm already doing this tutorial a few days ago to learn how to make drawing apps.

link

link

I have the following code that I am studying and trying to decipher its operation, and I have several doubts about it.

1) what is the canvasPaint type of Paint? How is it different from drawPaint ? What should I use it for?

2) in the setBrushSize (float newSize) method the values of newSize I receive a fragment with a SnackBar and the data arrives correctly to the method, however when I set the brush size to canvasPaint the latter does not affect anything. I tried to set drawPaint and it resizes but also applies the style to the entire drawing already made. How do I apply different brush styles without changing the entire previous drawing?

private static final String LOG_CAT = CustomView.class.getSimpleName();
private Path drawPath; // trazado de dibujo
private Paint canvasPaint; // define qué dibujar
private Paint drawPaint; // define cómo dibujar
private int paintColor =0xFF666fff; // color inicial
private Canvas drawCanvas; // lienzo - pluma de sujeción, sostiene tus dibujos y los transfiere a la vista
private Bitmap canvasBitmap; // mapa de bits del lienzo
private float currentBrushSize, lastBrushSize; //tamaño del pincel
private ArrayList<Path> paths = new ArrayList<Path>(); //las rutas que se dibujan en la pantalla
private ArrayList<Path> undonePaths = new ArrayList<Path>(); //las rutas que se han eliminado de la pantalla
private float mX,mY;
private static final float TOUCH_TOLERANCE = 4;
private boolean eraseMode = false;    //flag to set erase mode


public CustomView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}


private void init(){
    currentBrushSize = getResources().getInteger(R.integer.small_size);
    lastBrushSize = currentBrushSize;

    drawPath= new Path();

    drawPaint = new Paint();
    drawPaint.setColor(paintColor);
    drawPaint.setAntiAlias(true);
    drawPaint.setStrokeWidth(currentBrushSize);
    drawPaint.setStyle(Paint.Style.STROKE);
    drawPaint.setStrokeJoin(Paint.Join.ROUND);
    drawPaint.setStrokeCap(Paint.Cap.ROUND);

    canvasPaint = new Paint(Paint.DITHER_FLAG);

}

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

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    //Crea canvas del tamaño del dispositivo
    super.onSizeChanged(w, h, oldw, oldh);

    //Crea bitmap del tamañp w h
    canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

    // aplicar bitmap al gráfico para comenzar a dibujar.
    drawCanvas = new Canvas();
}


/** Set erase true or false */
public void setErase(boolean isErase){
    eraseMode = isErase;

    if(eraseMode){
        drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    } else {
        drawPaint.setXfermode(null);
    }
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    float touchX = event.getX();
    float touchY = event.getY();
    //respond to down, move and up events
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(touchX, touchY);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(touchX, touchY);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
        default:
            return false;
    }
    return true;
}

/**se llama a los métodos de inicio táctil cuando el dedo toca la pantalla
 * que se considera un evento MotionEvent.Action_Down y cuando esto sucede,
 * queremos borrar la lista de partes y restablecer el objeto Path.**/
private void touch_start(float x, float y) {
    undonePaths.clear();
    drawPath.reset();
    drawPath.moveTo(x, y);
    mX = x;
    mY = y;
}
/** cuando el usuario se movió del punto A al punto,
 * necesitaremos evaluar el valor de tolerancia que
 * establecemos en el último paso  **/
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) {
        drawPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
        mX = x;
        mY = y;
    }
}
/**cuando el usuario levanta su dedo de la pantalla,
 * queremos pintar lo que acaba de dibujar en la pantalla
 * y guardarlo en nuestro camino como este:**/
private void touch_up() {
    drawPath.lineTo(mX, mY);
    drawCanvas.drawPath(drawPath, drawPaint);
    paths.add(drawPath);
    drawPath = new Path();


}
/**limpia la pantalla**/
public void eraseAll() {
    drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    paths.clear();
    undonePaths.clear();
    invalidate();
}
//Deshacer
public void onClickUndo () {
    if (paths.size()>0)
    {
        undonePaths.add(paths.remove(paths.size()-1)); // remueve el ultimo Path y lo agrega a los path removidos
        invalidate();
    }

}
//Rehacer
public void onClickRedo (){
    if (undonePaths.size()>0)
    {
        paths.add(undonePaths.remove(undonePaths.size()-1));  // elimina el ultimo Path removido y lo vuelve a agregar al Path
        invalidate();
    }
}

//method to set brush size
public void setBrushSize(float newSize) {
    float pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            newSize, getResources().getDisplayMetrics());
    currentBrushSize = pixelAmount;
    canvasPaint.setStrokeWidth(newSize);
}

public void setLastBrushSize(float lastSize){
    lastBrushSize=lastSize;

}

public float getLastBrushSize(){
    return lastBrushSize;
}

Thank you very much!

    
asked by Leandro Gutierrez 27.01.2018 в 17:42
source

0 answers