I have a customview where i display two rectangles. i want to set the height by a variable i sent from the mainactivity.
my customview class is the following.
package com.example.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
Paint paint;
Paint paint2;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint2 = new Paint();
}
#Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
paint2.setColor(Color.DKGRAY);
canvas.drawRect(150, 0, 200, 100, paint);
canvas.drawRect(200, 0, 250, 150, paint2);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(400, 300);
}
}
And the mainclass is standard
package com.example.customview;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
how can i change the height from the oncreate or onstart.
Thanks all for helping.
You need create a varibale and set it from Activity. For example:
private int mHeight = 0;
#Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
paint2.setColor(Color.DKGRAY);
canvas.drawRect(150, 0, 200, 150 + mHeight, paint);
canvas.drawRect(200, 0, 250, 200 + mHeight, paint2);
}
public void setRectHeight(final int height) {
mHeight = height;
invalidate();
}
And set the height in your activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView view = (MyView)findViewById(R.id.my_view);
view.setHeight(50);
}
you need to send data from main activity and receive it from MyView. when you create the intent for opening new activity from main use
_YourIntent_.putExtra(_tag_,_yourData_);
startActivityForResult(_YourIntent_, result);
//put extra is simply for sending data, and to receive it the other hand , oncreate use this;
Intent x = getIntent();``
//now get the data
int _yourvariable_ = x.getExtras().getString(_tag_).toint;
Related
Hey guys I'm trying to use this library (https://github.com/davemorrissey/subsampling-scale-image-view) and I tried out the example mentioned about PinView but I don't get the map displayed nor any Marker. ( the error says cannot cast Subsampling ImageView as PinView how do you solve this ?
MainActivity.java
package com.ascot.mxiv.mapzone;
import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.ImageSource;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PinView imageView = findViewById(R.id.imageView);
imageView.setImage(ImageSource.resource(R.drawable.completemap1).tilingDisabled());
imageView.setPin(new PointF(460f, 320f));
}
}
PinView.java ( no changes made other than the import test.T.drawable as i dont understand it ) and help would be appreciated :D .
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
//import com.davemorrissey.labs.subscaleview.test.R.drawable;
public class PinView extends SubsamplingScaleImageView {
private final Paint paint = new Paint();
private final PointF vPin = new PointF();
private PointF sPin;
private Bitmap pin;
Context context;
public PinView(Context context) {
this(context, null);
this.context = context;
}
public PinView(Context context, AttributeSet attr) {
super(context, attr);
this.context = context;
initialise();
}
public void setPin(PointF sPin) {
this.sPin = sPin;
initialise();
invalidate();
}
private void initialise() {
float density = getResources().getDisplayMetrics().densityDpi;
pin = BitmapFactory.decodeResource(this.getResources(), R.drawable.marker);
float w = (density/420f) * pin.getWidth();
float h = (density/420f) * pin.getHeight();
pin = Bitmap.createScaledBitmap(pin, (int)w, (int)h, true);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Don't draw pin before image is ready so it doesn't move around during setup.
if (!isReady()) {
return;
}
paint.setAntiAlias(true);
if (sPin != null && pin != null) {
sourceToViewCoord(sPin, vPin);
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paint);
Toast.makeText(context,"works ? ", Toast.LENGTH_SHORT).show();
}
}
}
The problem is your in your layout, you should use PinView instead of SubsamplingScaleImageView as shown in the snippet below.
..
<com.example.myapp.PinView
android:id="#+id/floorplan_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
I want to display some text on Screen when the user clicks a button with canvas in android studio. I have been looking at many posts and videos of how to do that. The problem, when I tried their code, when I clicked my button, nothing showed up. Anyone know what I am doing wrong?
Here is my Java class:
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button drawCanvas = findViewById(R.id.draw_canvas_button);
drawCanvas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Paint paint = new Paint();
Canvas canvas = new Canvas();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(20f);
canvas.drawText("My Text", 10f, 15f, paint);
}
});
}
}
It seems that you have to use a method called onDraw by importing View.
import android.view.View;
public class myClass extends View{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
//Where you put the code
}
I am trying to implement an imageview with a diagonal cut at the bottom that I will user to display images on my app. This is the approach I take
I create a custom class that extends the ImageView.
I then override the onDraw method to draw the shape(This is where I'm not sure if I'm doing the correct thing
My custom imageview class
public class DiagonalSquare extends ImageView {
private Context mContext;
Paint paint ;
Path path;
public DiagonalSquare(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
setWillNotDraw(false);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected void onDraw(Canvas canvas) {
int w = getWidth(), h = getHeight();
paint.setStrokeWidth(2);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(w,h*3/4);
path.lineTo(w,h);
path.lineTo(0,h);
path.close();
canvas.drawPath(path, paint);
}
}
This is what I end up getting - blue section is the imageview. Here is the xml for that
<com.noel.CustomShape.DiagonalSquare
android:id="#+id/background_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
android:src="#drawable/bebe" />
You are missing a call to super.onDraw(canvas);
In addition to #Dimezis answer: If you want to have transparent effect on the ImageView background you have to clear hardware layer type and also set Xfermode for pain like in following example:
package com.j2ko.customviews;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CustomImageView extends ImageView {
private Context mContext;
Paint paint ;
Path path;
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
setWillNotDraw(false);
//Move to XML if needed
setBackgroundColor(Color.TRANSPARENT);
setLayerType(LAYER_TYPE_HARDWARE, null);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth(), h = getHeight();
paint.setStrokeWidth(2);
paint.setColor(Color.WHITE);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(w,h*3/4);
path.lineTo(w,h);
path.lineTo(0,h);
path.close();
canvas.drawPath(path, paint);
}
}
This will give the following results:
I have an app that displays random characters vertically on the screen (like in the matrix movie) and I would like to add buttons to change the color of these chars when pressed, but I'm unable to call the method setColor of paintTxt variable from MainActivity.
This is my code,
EffetMatrix effetMatrix = new EffetMatrix();//Error in ()
final Paint paintTxt = effetMatrix.paintTxt;
paintTxt.setColor(Color.RED);
But the editor shows an error:
EffetMatrix(Context, AttributSet) in EffetMatrix cannot be applied to ()
the EffetMatrix class code
package com.esqmo.apps.effetmatrix;
import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.content.Context;
import android.widget.Button;
/**
* Created by esQmo on 04/10/2016.
*/
public class EffetMatrix extends View {
private static final Random ALEATOIRE = new Random();
private int larg, haut;
private Canvas toile;
private Bitmap toileBmp;
private int taillePolice = 40;
private int tailleColonne;
private char[] chars = "01".toCharArray();
private int[] posTxtParColonne;
public Paint peindreTxt, peindreArrPlan, peindreArrPlanBmp, peindreInitArrPlan;
public EffetMatrix(Context context, AttributeSet attrs) {
super(context, attrs);
peindreTxt = new Paint();
peindreTxt.setStyle(Paint.Style.FILL);
peindreTxt.setColor(Color.BLUE);
peindreTxt.setTextSize(taillePolice);
peindreArrPlan = new Paint();
peindreArrPlan.setStyle(Paint.Style.FILL);
peindreArrPlan.setColor(Color.BLACK);
peindreArrPlan.setAlpha(5);
peindreArrPlanBmp = new Paint();
peindreArrPlanBmp.setColor(Color.BLACK);
peindreInitArrPlan = new Paint();
peindreInitArrPlan.setColor(Color.BLACK);
peindreInitArrPlan.setAlpha(255);
peindreInitArrPlan.setStyle(Paint.Style.FILL);
}
#Override
protected void onSizeChanged(int l, int h, int ancl, int anch) {
super.onSizeChanged(l, h, ancl, anch);
larg = l;
haut = h;
toileBmp = Bitmap.createBitmap(larg, haut, Bitmap.Config.ARGB_8888);
toile = new Canvas(toileBmp);
toile.drawRect(0, 0, larg, haut, peindreInitArrPlan);
tailleColonne = larg / taillePolice;
posTxtParColonne = new int[tailleColonne + 1];
for (int x = 0; x < tailleColonne; x++) {
posTxtParColonne[x] = ALEATOIRE.nextInt(larg / 2) + 1;
}
}
private void dessineTexte() {
for (int i = 0; i < posTxtParColonne.length; i++) {
toile.drawText("" + chars[ALEATOIRE.nextInt(chars.length)], i * taillePolice,
posTxtParColonne[i] * taillePolice, peindreTxt);
if (posTxtParColonne[i] * taillePolice > larg && Math.random() > 0.980) {
posTxtParColonne[i] = 0;
}
posTxtParColonne[i]++;
}
}
private void dessineToile() {
toile.drawRect(0, 0, larg, haut, peindreArrPlan);
dessineTexte();
}
#Override
protected void onDraw(Canvas toile) {
super.onDraw(toile);
toile.drawBitmap(toileBmp, 0, 0, peindreArrPlanBmp);
dessineToile();
invalidate();
}
public void setCustomColor(int color){
peindreTxt.setColor(color);
invalidate();
}
}
note: variable peindreText = paintText
The main activity code:
package com.esqmo.apps.effetmatrix;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.effect.Effect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button boutton_vert = (Button) findViewById(R.id.b_v);
final Button boutton_bleu = (Button) findViewById(R.id.b_b);
final Button boutton_rouge = (Button) findViewById(R.id.b_r);
final Button boutton_rose = (Button) findViewById(R.id.b_ro);
boutton_bleu.setOnClickListener(this);
boutton_vert.setOnClickListener(this);
boutton_rouge.setOnClickListener(this);
boutton_rose.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
public void passerVert(View v) {
}
public void passerRouge(View v) {
}
public void passerRose(View v) {
}
public void passerBleu(View v) {
}
}
main.xml
<com.esqmo.apps.effetmatrix.EffetMatrix
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/arrPlan"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#040404"
android:id="#+id/linearLayout">
<Button
android:layout_width="70dp"
android:layout_height="match_parent"
android:text="#string/button_vert"
android:onClick="passerVert"
android:id="#+id/b_v"
android:textAppearance="#android:color/holo_blue_dark" />
<Button
android:layout_width="70dp"
android:layout_height="match_parent"
android:text="#string/button_bleu"
android:onClick="passerBleu"
android:id="#+id/b_b"/>
<Button
android:layout_width="70dp"
android:layout_height="match_parent"
android:text="#string/button_rouge"
android:onClick="passerRouge"
android:id="#+id/b_r" />
<Button
android:layout_width="70dp"
android:layout_height="match_parent"
android:text="#string/button_rouge"
android:onClick="passerRose"
android:id="#+id/b_ro" />
</LinearLayout>
PS: I'm a noob in programming.
Sorry for my english
Don't create a new instance of the custom view again. Instead get a reference to the view using its id.
See the following code,
EffetMatrix effetMatrix = (EffetMatrix) findViewById(R.id.arrPlan);
effetMatrix.setCustomTextColor(Color.RED);
Inside EffetMatrix class create a method named setCustomColor as follows,
class EffetMatrix {
...
public void setCustomTextColor(int color){
// Set the color to the paintTxt object
paintTxt.setColor(color);
// invalidate the view to apply the changes
invalidate();
}
...
}
This is how you implement it in your code,
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EffetMatrix effetMatrix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
effetMatrix = (EffetMatrix) findViewById(R.id.arrPlan);
...
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.b_b:
effetMatrix.setCustomTextColor(Color.BLUE);
break;
case R.id.b_r:
effetMatrix.setCustomTextColor(Color.RED);
break;
case R.id.b_ro:
effetMatrix.setCustomTextColor(Color.MAGENTA);
break;
}
}
}
You must invalidate your custom view after changing paint color.
effetMatrix.invalidate();
And if you want to display your custom view in editor you must implement :
public EffetMatrix(Context context) {
this(context, null);
}
public EffetMatrix(Context context, AttributeSet attrs) {
super(context, attrs);
}
If you want to make the buttons do something, then you have to set an onClickListener for each button in your main properly. Here's an example for button_bleu,
Get rid of boutton_bleu.setOnClickListener(this); and replace it with
button_bleu.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
effetMatrix.setCustomColor(Color.BLUE);
}
});
Now just do the same for the other 3 buttons.
I'm trying to create a simple drawing app that allows you to draw on a canvas, and you're able to change the color and thickness of it. The problem that's occurring is that every time I try to change the color or thickness of the paint, it changes ALREADY existing paint that's on the canvas. I understand why it's not working, but I just don't know how to fix it and where exactly the problem lies.
CanvasView Class
package samkough.com.painter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
public class CanvasView extends View
{
/*
* When the user touches the screen and moves their finger to draw,
* we will use a Path to trace their drawing action on the canvas.
* Both the canvas and the drawing on top of it are represented by Paint
* objects. The initial paint color corresponds to the first color
* in the palette we created last time, which will be initially selected
* when the app launches. Finally we declare variables for the canvas
* and bitmap - the user paths drawn with drawPaint will be drawn onto
* the canvas, which is drawn with canvasPaint.
* */
//drawing paint
private Paint paint = new Paint();
// canvas paint
private Paint canvasPaint = new Paint();
//drawing path
private Path path = new Path();
// canvas
private Canvas canvas = new Canvas();
//canvas bitmap
private Bitmap canvasBitmap;
// brush size and pixel size
private float brushSize, pixelAmount;
public CanvasView(Context context, AttributeSet attrs)
{
// Setting the anti-alias, stroke join and cap styles will make the user's drawings appear smoother.
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas drawCanvas)
{
drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
drawCanvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent e)
{
// get the coords of the touch event
float eventX = e.getX();
float eventY = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
// set a new starting point
path.moveTo(eventX, eventY);
path.reset();
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
// makes you view repaint and call ondraw
invalidate();
return true;
}
public void clearCanvas()
{
path.reset();
invalidate();
}
public void setStrokeWidth(float f)
{
pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, f, getResources().getDisplayMetrics());
brushSize = pixelAmount;
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(brushSize);
invalidate();
}
public void setColor(int p)
{
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setColor(p);
invalidate();
}
}
MainActivity Class
package samkough.com.painter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import com.samkough.painter.R;
public class MainActivity extends Activity {
private CanvasView canvasView;
private int orange;
private int purple;
private float strokeWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvasView = (CanvasView) findViewById(R.id.canvasView);
orange = Color.rgb(250, 128, 0);
purple = Color.rgb(128, 0, 128);
strokeWidth = 0;
// REGULAR BUTTONS: save, about, reset
Button saveB = (Button) findViewById(R.id.saveButton);
Button aboutB = (Button) findViewById(R.id.aboutButton);
Button resetB = (Button) findViewById(R.id.resetButton);
// IMAGE BUTTONS: red, blue, green, yellow, black, purple, orange, erase, brush thickness plus, brush thickness minus
ImageButton redIb = (ImageButton) findViewById(R.id.redButton);
ImageButton blueIb = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenIb = (ImageButton) findViewById(R.id.greenButton);
ImageButton yellowIb = (ImageButton) findViewById(R.id.yellowButton);
ImageButton blackIb = (ImageButton) findViewById(R.id.blackButton);
ImageButton purpleIb = (ImageButton) findViewById(R.id.purpleButton);
ImageButton orangeIb = (ImageButton) findViewById(R.id.orangeButton);
ImageButton eraseIb = (ImageButton) findViewById(R.id.eraseButton);
ImageButton plusIb = (ImageButton) findViewById(R.id.plusButton);
ImageButton minusIb = (ImageButton) findViewById(R.id.minusButton);
minusIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
strokeWidth -= 2;
canvasView.setStrokeWidth(strokeWidth);
}
});
plusIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strokeWidth += 2;
canvasView.setStrokeWidth(strokeWidth);
}
});
eraseIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.TRANSPARENT);
}
});
orangeIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(orange);
}
});
purpleIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(purple);
}
});
blackIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.BLACK);
}
});
yellowIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.YELLOW);
}
});
greenIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.GREEN);
}
});
blueIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.BLUE);
}
});
redIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.setColor(Color.RED);
}
});
saveB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
aboutB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent);
}
});
resetB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.clearCanvas();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have created canvas, but you are not using that to draw anything on it. So essentially, the line drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint); doesn't do anything.
What you need to do instead is draw the path on the canvas. Then draw the canvasBitmap using drawCanvas. This way you can maintain a single path and a single paint instead of multiple ones.
#Override
protected void onDraw(Canvas drawCanvas)
{
canvas.drawPath(path, paint);
drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
}
When you do the above, each time the user draw's a new path, the canvasBitmap will hold all the old paths in it. So each time the onDraw is called, only the new path is drawn.
Always remember: It's a bad practice to create multiple PAINT objects. Try to reuse the Paint object as much as possible.
In CanvasView.java, this line
private Paint paint = new Paint();
declares one paint object for the whole class, and this line
private Path path = new Path();
declares one path object for the whole class.
When onDraw is called, your whole canvas area is being redrawn. That means that
drawCanvas.drawPath(path, paint);
is drawing the entire path that has been added since the activity was created with whatever the current value of paint is.
One way of working around this is to have a list of Path objects and a list of Paint objects. The first element of the Path list would store the first path that was drawn--say, everything drawn up until the point when they change paint. The first element of the paint list would store the corresponding paint that was used. Whenever the user changes the paint and begins painting, you'll need to create a new Path object, and add it and the new Paint object to the lists.
Once you have lists of the paths and the paints they were drawn with, you can do something like this in onDraw:
for (int i = 0; i < paths.size(); i++) {
Path path = paths.get(i);
Paint paint = paints.get(i);
drawCanvas.drawPath(path, paint);
}