I have been looking for help doing this, I am attempting to create a snake game, what I need to do is draw into a bitmap or into an image view while clicking a button, that's the problem: every time I draw a shape, then the layout is erased, the goal for me is to draw into any object while I can still click a button, what I have already done is to draw over a layout and displaying an image, here is my code:
public class DisplayMessage extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra("Hola Jorge");
DrawView drawView;
drawView = new DrawView(this);
setContentView(drawView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
}
package mipaca;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
//canvas.drawColor(Color.GREEN);
canvas.drawLine(0, 0, 20, 20, paint);
canvas.drawLine(20, 0, 0, 20, paint);
Bitmap compara = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
canvas.drawBitmap(compara, 0, 0, paint);
Rect rectangle = new Rect(0,0,100,100);
canvas.drawBitmap(compara, 0,0,null);
}
}
public class MainActivity extends Activity {
CharSequence[] items = {"Google","Apple","Microsoft"};
boolean[] itemsChecked = new boolean[items.length];
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick2(View v)
{
Intent intent = new Intent(this, DisplayMessage.class);
startActivity(intent);
}
public void onClick(View v)
{
//image.setImageResource(R.drawable.ferrari_458_italia_1);
showDialog(0);
DrawView2 alpha;
}
#Override
protected Dialog onCreateDialog(int id){
switch(id){
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("Este es un diálogo con algo de texto")
.setPositiveButton("OK",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), "bien, click!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), "bien, click!", Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
public void onDraw(Canvas canvas)
{
Paint p = new Paint();
p.setColor(Color.BLUE);
p.setAntiAlias(true);
canvas.drawColor(Color.CYAN);
canvas.drawCircle(200, 200, 50, p);
}
}
I hope this help someone, I forgot about this question until I came across with this idea: We can use an ImageView and then use a bitmap to draw any shape with a canvas, it is easier for me to draw in this way rather than using OnPaint function and invalidate because just modifying the bitmap and displaying it we can move an object on image and still have buttons, textboxs, etc. Here is what I have done:
(linen is our ImageView)
Bitmap bMap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
android.graphics.Bitmap.Config bitmapConfig = bMap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bMap = bMap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bMap);
paint.setColor(Color.rgb(61, 61, 61));
canvas.drawCircle(10, 10, 5, paint);
linen = (ImageView)findViewById(R.id.View1);
linen.setImageBitmap(bMap);
Related
Canvas Painting is not reset when Click ,It is reset when I am drawing again on canvas after click the clear button.............................................................................................................................................................................................................................................................................................................................................................................
HERE IS MY CODE
public class Practice extends FragmentActivity {
private RelativeLayout relativeLayout;
private Paint paint;
ImageView back;
private View view;
private Path path2;
private Bitmap bitmap;
private Canvas canvas;
private Button button;
public int width, height;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice);
back = findViewById(R.id.back);
relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout1);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
button = (Button) findViewById(R.id.button);
view = new SketchSheetView(Practice.this);
paint = new Paint();
path2 = new Path();
relativeLayout.addView(view, new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
paint.setDither(true);
paint.setColor(Color.parseColor("#FFFFFF"));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.MITER);
paint.setStrokeCap(Paint.Cap.BUTT);
paint.setStrokeWidth(5);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
path2.reset();
}
});
}
class SketchSheetView extends View {
public SketchSheetView(Context context) {
super(context);
bitmap = Bitmap.createBitmap(100, 200, Bitmap.Config.ARGB_4444);
canvas = new Canvas(bitmap);
this.setBackground(getResources().getDrawable(R.drawable.ic_brush_black_24dp));
}
private ArrayList<DrawingClass> DrawingClassArrayList = new ArrayList<DrawingClass>();
#Override
public boolean onTouchEvent(MotionEvent event) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
DrawingClass pathWithPaint = new DrawingClass();
canvas.drawPath(path2, paint);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
this.setBackground(null);
vibrator.vibrate(500);
path2.moveTo(event.getX(), event.getY());
path2.lineTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
this.setBackground(null);
path2.lineTo(event.getX(), event.getY());
vibrator.vibrate(500);
pathWithPaint.setPath(path2);
pathWithPaint.setPaint(paint);
DrawingClassArrayList.add(pathWithPaint);
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (DrawingClassArrayList.size() > 0) {
canvas.drawPath(
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPath(),
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPaint()
);
}
}
}
public class DrawingClass {
Path DrawingClassPath;
Paint DrawingClassPaint;
public Path getPath() {
return DrawingClassPath;
}
public void setPath(Path path) {
this.DrawingClassPath = path;
}
public Paint getPaint() {
return DrawingClassPaint;
}
public void setPaint(Paint paint) {
this.DrawingClassPaint = paint;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
I have created a simple drawing app, in which i am using a seek bar to get stroke width. But as soon as i change the stroke width, the width of complete drawing changes. Same happens when i change the pen color. How to individually assign stroke attributes to each path?
I have tried many answers but could not get the correct result.
I have tried storing the path and the respective paint associated with it and then drawing it. but that too didn't work.
public class MainActivity extends AppCompatActivity {
View mView;
private Paint mPaint;
SeekBar mSeekbar;
int penColor = Color.BLACK;
int bgColor = Color.WHITE;
int StrokeWidth = 12;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.myDrawing);
mView = new DrawingView(this);
mSeekbar = (SeekBar) findViewById(R.id.seek);
mSeekbar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
mSeekbar.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
layout.addView(mView, new ActionBar.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
((DrawingView) mView).init();
penSize();
}
public void penSize() {
mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
((DrawingView) mView).changePenSize(StrokeWidth);
StrokeWidth = i;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
((DrawingView) mView).changePenSize(StrokeWidth);
}
});
}
class DrawingView extends View {
private Path path;
private Bitmap mBitmap;
private Canvas mCanvas;
public DrawingView(Context context) {
super(context);
path = new Path();
mBitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
this.setBackgroundColor(bgColor);
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(penColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(StrokeWidth);
}
public void changePenSize(int size) {
StrokeWidth = size;
mPaint.setStrokeWidth(StrokeWidth);
invalidate();
}
public void init() {
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(penColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(StrokeWidth);
}
public void setBGColor(int color) {
bgColor = color;
this.setBackgroundColor(bgColor);
invalidate();
}
public void ClearPath() {
path.reset();
bgColor = Color.WHITE;
penColor = Color.BLACK;
init();
invalidate();
}
public void changePenColor() {
mPaint.setColor(penColor);
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
mCanvas.drawPath(path, mPaint);
break;
default:
return false;
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, mPaint);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
File myDir = new File(Environment.getExternalStorageDirectory(),
"Drawings");
myDir.mkdirs();
Date now = new Date();
String fname = "image" + now.getDate() + now.getSeconds() + ".jpg";
File file = new File(myDir, fname);
//noinspection SimplifiableIfStatement
if (id == R.id.clear) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Do you really want to clear ?\nYou can save before clearing.");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
((DrawingView) mView).ClearPath();
Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.show();
return true;
} else if (id == R.id.bgColor) {
bgColor();
} else if (id == R.id.penColor) {
penColor();
} else if (id == R.id.screenshot) {
takeScreenshot();
return true;
}
return super.onOptionsItemSelected(item);
}
private void penColor() {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(MainActivity.this, Color.BLACK, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
penColor = color;
((DrawingView) mView).changePenColor();
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
}
});
dialog.show();
}
private void bgColor() {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(MainActivity.this, Color.BLACK, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
bgColor = color;
((DrawingView) mView).setBGColor(bgColor);
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
}
});
dialog.show();
}
private void takeScreenshot() {
mView.setDrawingCacheEnabled(true);
String filename= UUID.randomUUID().toString() + ".png";
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), mView.getDrawingCache(),
filename, "drawing");
if (imgSaved != null) {
Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery! ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT).show();
}
mView.destroyDrawingCache();
}
}
class DrawingView extends View {
ArrayList<DrawingPath> paths;
private DrawingPath drawingPath;
private Bitmap mBitmap;
private Canvas mCanvas;
public DrawingView(Context context) {
super(context);
paths = new ArrayList<>();
mBitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
this.setBackgroundColor(bgColor);
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(penColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(StrokeWidth);
}
public void changePenSize(int size) {
StrokeWidth = size;
mPaint.setStrokeWidth(StrokeWidth);
}
public void init() {
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(penColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(StrokeWidth);
}
public void setBGColor(int color) {
bgColor = color;
this.setBackgroundColor(bgColor);
invalidate();
}
public void ClearPath() {
paths.clear();
bgColor = Color.WHITE;
penColor = Color.BLACK;
init();
invalidate();
}
public void changePenColor() {
mPaint.setColor(penColor);
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawingPath = new DrawingPath(mPaint.getStrokeWidth());
paths.add(drawingPath);
drawingPath.path.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawingPath.path.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
mCanvas.drawPath(drawingPath.path, mPaint);
break;
default:
return false;
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (DrawingPath drawingPath : paths) {
mPaint.setStrokeWidth(drawingPath.strokeWidth);
canvas.drawPath(drawingPath.path, mPaint);
}
}
}
class DrawingPath {
Path path;
float strokeWidth;
DrawingPath(float strokeWidth) {
path = new Path();
this.strokeWidth = strokeWidth;
}
}
I hope this will help. You can other properties like color,style, etc to DrawingPath model.
here is my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_layer_drawable2);
ImageView i = (ImageView) findViewById(R.id.i);
LayerDrawable ld = new LayerDrawable(new Drawable[]{dra(this, R.drawable.ic_insert_drive_file_black_48dp), new Rect()});
ld.setLayerInsetTop(1, 200);
ld.setLayerInsetLeft(1, 200);
i.setImageDrawable(ld);
}
here is Rect
class Rect extends Drawable {
Context c;
#Override
public void draw(Canvas canvas) {
c = getApplicationContext();
Paint p = new Paint();
p.setStrokeWidth(2);
p.setStyle(Paint.Style.STROKE);
p.setColor(col(c, R.color.colorAccent));
canvas.drawRect(100, 100, 200, 200, p);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return 0;
}
}
the output is:
I hope move rectangle to the right-bottom of ImageView, how to do that?
when i use setLayerInsetTop, it only change rectangle's size
I find the reason, in Rect class canvas.drawRect(0, 0, 100, 100, p), it will force rect locate in pointer (0, 0), I can change "0,0" to other
I am making an android colouring app which uses the draw feature. I have it so that there are multiple colours that the user can choose from and they can select a colour and draw however when they select a new colour it changes all previously drawn lines as well not just the new lines being drawn. Any help on how I can rectify this and have multiple colours used on the drawing is greatly appreciated. Some of my code is below: The first is the colouring class
public class Colouring extends View {
// setup initial color
private int paintColor = Color.BLACK;
private Paint drawPaint;
private Path drawPath;
// stores the path
//private Path path = new Path();
public Colouring(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupcolour();
}
private void setupcolour() {
// Setup paint with color and stroke styles
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(15);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(drawPath, drawPaint);
}
public void setColor(String newColor) {
invalidate();
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(pointX, pointY);
break;
default:
return false;
}
// Force a view to draw again
invalidate();
return true;
}
}
and the second is the main activity where the drawing happens.
public class ColourImage extends Activity {
private Colouring drawView;
private ImageButton currcolour, save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colour_image);
drawView = (Colouring)findViewById(R.id.colouringBook);
LinearLayout paintLayout = (LinearLayout) findViewById(R.id.colours);
currcolour = (ImageButton) paintLayout.getChildAt(0);
currcolour.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
save = (ImageButton)findViewById(R.id.save);
}
public void saveclicked(View view){
drawView.setDrawingCacheEnabled(true);
String saveImage = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(),
UUID.randomUUID().toString()+".png", "colouredImage");
if(saveImage!=null){
Toast savedToast = Toast.makeText(getApplicationContext(),
"Your colouring has been saved to your phone", Toast.LENGTH_SHORT);
savedToast.show();
}
else{
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Your colouring was not saved", Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
}
public void paintClicked(View view){
if(view!=currcolour){
ImageButton colourImage = (ImageButton)view;
String color = view.getTag().toString();
drawView.setColor(color);
colourImage.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
currcolour.setImageDrawable(getResources().getDrawable(R.drawable.paint));
currcolour=(ImageButton)view;
}
}
}
Thanks again :)
I'm working an app which is can draw on a custom view. I want to save the drawing with a button. I tried the other solution on the other threads but nothing. please give me an example with my method below. actually, it's not my method. it's from https://github.com/msiuts/FingerPaint
Custom View
DrawView.java
public class DrawView extends View implements OnTouchListener {
private static final String TAG = "DrawView";
private final Random random = new Random();
private final int[] colors = new int[] {Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK};
private final Paint paint = new Paint();
private Path path = new Path();
private Canvas canvas;
private Bitmap bitmap;
// deletes the screen by painting it black when the Menu Button is pressed
// this is a good method but how about save the drawing?
private OnKeyListener clearingOnKeyListener = new OnKeyListener() {
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (KeyEvent.KEYCODE_MENU == keyEvent.getKeyCode() && KeyEvent.ACTION_DOWN == keyEvent.getAction()) {
bitmap.eraseColor(Color.BLACK);
invalidate();
return true;
}
return false;
}
};
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
this.setOnKeyListener(clearingOnKeyListener);
paint.setColor(randomColor());
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (bitmap != null) {
if (bitmap.getHeight() == w && bitmap.getWidth() == h) {
Log.d(TAG, "rotating bitmap by 90 degree");
Matrix mtx = new Matrix();
mtx.postRotate(90, h/2, w/2);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, h, w, mtx, false);
canvas = new Canvas();
canvas.setBitmap(bitmap);
return;
} else {
bitmap.recycle();
}
}
canvas = new Canvas();
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
}
#Override
public void onDraw(Canvas c) {
// draw to the screen
c.drawBitmap(bitmap, null, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), null);
}
public boolean onTouch(View view, MotionEvent event) {
// draw the new Points to our internal canvas / bitmap
if (event.getAction() == MotionEvent.ACTION_DOWN) {
paint.setColor(randomColor());
path = new Path();
path.moveTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
int historySize = event.getHistorySize();
for (int i=0; i < historySize; i++) {
path.lineTo(event.getHistoricalX(i), event.getHistoricalY(i));
}
path.lineTo(event.getX(), event.getY());
canvas.drawPath(path, paint);
} else {
return super.onTouchEvent(event);
}
invalidate();
return true;
}
public Bitmap getBitmap() {
return bitmap;
}
public void initBitmap(Bitmap bmap) {
bitmap = bmap;
}
/**
* Chooses a random color.
* #return the chosen color
*/
private int randomColor() {
return colors[random.nextInt(colors.length)];
}
}
Activity
Drawing Activity.java
public class DrawingActivity extends Activity {
private static final String TAG = "FingerPaint";
private DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
// restore view
drawView = (DrawView) findViewById(R.id.drawView);
Log.d(TAG, "DrawView from R is null? " + (drawView == null));
Bitmap lastDrawing = (Bitmap) getLastNonConfigurationInstance();
if (lastDrawing != null) {
Log.d(TAG, "lastDrawing is not null");
drawView.initBitmap(lastDrawing);
}
}
#Override
public Object onRetainNonConfigurationInstance() {
Bitmap bmap = null;
if (drawView != null) {
bmap = drawView.getBitmap();
Log.d(TAG, "onRetainNonConfigurationInstance returning a bitmap: " + (bmap != null));
}
return bmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
On the assumption you want to save the file to the devices storage, here is the solution i use...
Add permission to manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here is how I am doing it:
// Variables i needed
private String mFileName;
private Bitmap mBitmap;
// apply this listener to your button
private final View.OnClickListener ButtonListener = new View.OnCickListener(){
#Override
public void onClick(View v){
new SaveFile().execute();
}
}
private class SaveFile extends AsyncTask<Void, Void, File>{
#Override
protected File doInBackground(Void... params) {
View rootView = findViewById(R.id.drawView);
File newBackgroundBitmap = saveFileToStorage(rootView);
return newBackgroundBitmap;
}
#Override
protected void onPostExecute(File bitmapFile) {
super.onPostExecute(bitmapFile);
if(bitmapFile != null){
Toast.makeText(getBaseContext(), "Saved drawView to storage", Toast.LENGTH_SHORT).show();
}
}
}
Then here is the method doing all the work:
/**
* Saves the Bitmap File to Storage and returns the new File
* #param rootView - the View we want to capture
* #return returns the new FileName of the image.
*/
private File saveFileToStorage(View rootView){
rootView.setDrawingCacheEnabled(true);
mBitmap = rootView.getDrawingCache();
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "FOLDER_NAME_YOU_WANT_TO_USE");
fileDirectory.mkdirs();
// Filename to store, Probably want to add some time stamp to make this unique
mFileName = "YOUR_FILE_NAME"+ ".png";
final File newBackgroundBitmap = new File(fileDirectory, mFileName);
try{
newBackgroundBitmap.createNewFile();
FileOutputStream outputStream = new FileOutputStream(newBackgroundBitmap);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.close();
Log.d(TAG, "File saved..." + " " + mFileName);
}catch(Exception e){
e.printStackTrace();
}
return newBackgroundBitmap;
}