I am currently developing a coloring app for the kids. Created a canvas of an image for coloring. The image is a PNG and I am trying to color the image so the image does not get covered by the paint or color. I am very close in building the app but the problem is that I am not getting the tip of coloring the image in a way so that the image remains on the front and the color on the back
Here is my code
public class FingerPaint extends Activity {
LinearLayout mainContainer;
LinearLayout buttonContainer;
LinearLayout.LayoutParams ![enter image description here][1]btnParams;
Button btnText, btnSketch, btnColor, btnUndo, btnRedo, btnDone,btnClear;
// MyView drawView;
DrawingPanel drawView;
int lastColor = 0xFFFF0000;
public static final int SUCCESS = 200;
private final String TAG = getClass().getSimpleName();
private String textToDraw = null;
private boolean isTextModeOn = false;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, mBitmapPaint;
private ArrayList<PathPoints> paths = new ArrayList<PathPoints>();
private ArrayList<PathPoints> undonePaths = new ArrayList<PathPoints>();
private Bitmap mBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
generateViews();
}
public static void displayAlert(Context context, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage(context.getString(R.string.app_name));
alert.setMessage(msg);
alert.setPositiveButton(context.getString(R.string.btn_ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private void generateViews() {
btnDone = new Button(this);
btnDone.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
btnDone.setText(getString(R.string.btn_done));
btnText = new Button(this);
btnClear = new Button(this);
btnSketch = new Button(this);
btnColor = new Button(this);
btnUndo = new Button(this);
btnRedo = new Button(this);
mainContainer = new LinearLayout(this);
mainContainer.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mainContainer.setOrientation(LinearLayout.VERTICAL);
buttonContainer = new LinearLayout(this);
buttonContainer.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
buttonContainer.setOrientation(LinearLayout.HORIZONTAL);
btnParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1);
btnText.setText("Text");
btnText.setLayoutParams(btnParams);
btnClear.setText("Clear");
btnClear.setLayoutParams(btnParams);
btnSketch.setText("Sketch");
btnSketch.setLayoutParams(btnParams);
btnColor.setText("Color");
btnColor.setLayoutParams(btnParams);
btnUndo.setText("Undo");
btnUndo.setLayoutParams(btnParams);
btnRedo.setText("Redo");
btnRedo.setLayoutParams(btnParams);
buttonContainer.addView(btnText);
buttonContainer.addView(btnClear);
buttonContainer.addView(btnSketch);
buttonContainer.addView(btnColor);
buttonContainer.addView(btnUndo);
buttonContainer.addView(btnRedo);
drawView = new DrawingPanel(this, lastColor);
drawView.setDrawingCacheEnabled(true);
drawView.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
drawView.layout(0, 0, drawView.getMeasuredWidth(),
drawView.getMeasuredHeight());
drawView.buildDrawingCache(true);
drawView.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1));
mainContainer.addView(btnDone);
mainContainer.addView(drawView);
mainContainer.addView(buttonContainer);
setContentView(mainContainer);
btnSketch.setSelected(true);
btnText.setOnClickListener(new OnClickListener() {
//text
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetButtons();
btnText.setSelected(true);
AlertDialog.Builder alert = new AlertDialog.Builder(
FingerPaint.this);
alert.setMessage(getString(R.string.msg_enter_text_to_draw));
final EditText edText = new EditText(FingerPaint.this);
alert.setView(edText);
alert.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
if (edText.getText().toString().length() > 0) {
textToDraw = edText.getText().toString();
isTextModeOn = true;
displayAlert(FingerPaint.this,
getString(R.string.msg_tap_image));
} else {
displayAlert(
FingerPaint.this,
getString(R.string.msg_enter_text_to_draw));
}
}
});
alert.setNegativeButton(R.string.btn_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
isTextModeOn = false;
}
});
alert.show();
}
});
/// clear
btnClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//mBitmap.eraseColor(Color.TRANSPARENT);
mPath.reset();
paths.removeAll(paths);
undonePaths.removeAll(undonePaths);
drawView.invalidate();
}
});
////sketch
btnSketch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetButtons();
btnSketch.setSelected(true);
isTextModeOn = false;
}
});
//color
/* btnColor.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AmbilWarnaDialog dialog = new AmbilWarnaDialog(
FingerPaint.this, lastColor,
new OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
// color is the color selected by the user.
colorChanged(color);
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
// cancel was selected by the user
}
});
dialog.show();
}
});*/
//undo
btnUndo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
drawView.onClickUndo();
}
});//redo
btnRedo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
drawView.onClickRedo();
}
});
//done
btnDone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*Log.v(TAG, "Here");
Bitmap editedImage = Bitmap.createBitmap(drawView
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, 200, 300,
true);
if (editedImage != null) {
Intent intent = new Intent();
//intent.putExtra(ChooseActivity.BITMAP, editedImage);
// AddReportItemActivity.mPhoto =
// drawView.getDrawingCache();
setResult(SUCCESS, intent);
finish();
}
}*/
AlertDialog.Builder editalert = new AlertDialog.Builder(FingerPaint.this);
editalert.setTitle("Please Enter the name with which you want to Save");
final EditText input = new EditText(FingerPaint.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
input.setLayoutParams(lp);
editalert.setView(input);
editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name= input.getText().toString();
Bitmap bitmap = drawView.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File("mnt/sdcard/"+name+".png");
try
{
if(!file.exists())
{
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
drawView.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}finally
{
drawView.setDrawingCacheEnabled(false);
}
}
});
editalert.show();
}
});
}
public void resetButtons() {
btnText.setSelected(false);
btnClear.setSelected(false);
btnSketch.setSelected(false);
btnColor.setSelected(false);
btnUndo.setSelected(false);
btnRedo.setSelected(false);
}
public class DrawingPanel extends View implements OnTouchListener {
private int color;
public int x, y;
public DrawingPanel(Context context, int color) {
super(context);
this.color = color;
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(15);
mPaint.setTextSize(30);
//mPaint.setStyle(Style s);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();
}
public void colorChanged(int color) {
this.color = color;
mPaint.setColor(color);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// mBitmap = AddReportItemActivity.mPhoto;
//mBitmap = getIntent().getExtras().getParcelable(ChooseActivity.BITMAP);
mBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(),
R.drawable.images);
// targetImage.setImageBitmap(srcBitmapLocal);
float xscale = (float) w / (float) mBitmap.getWidth();
float yscale = (float) h / (float) mBitmap.getHeight();
if (xscale > yscale) // make sure both dimensions fit (use the
// smaller scale)
xscale = yscale;
float newx = (float) w * xscale;
float newy = (float) h * xscale; // use the same scale for both
// dimensions
// if you want it centered on the display (black borders)
mBitmap = Bitmap.createScaledBitmap(mBitmap, this.getWidth(),
this.getHeight(), true);
// mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
for (PathPoints p : paths) {
mPaint.setColor(p.getColor());
Log.v("", "Color code : " + p.getColor());
if (p.isTextToDraw()) {
canvas.drawText(p.textToDraw, p.x, p.y, mPaint);
} else {
canvas.drawPath(p.getPath(), mPaint);
}
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
Point p=new Point();
private void touch_start(float x, float y) {
p.x=(int)x;
p.y=(int)y;
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;
int xx=Math.round(mX);
int yy=Math.round(mY);
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
}
private void drawText(int x, int y) {
Log.v(TAG, "Here");
Log.v(TAG, "X " + x + " Y " + y);
this.x = x;
this.y = y;
paths.add(new PathPoints(color, textToDraw, true, x, y));
// mCanvas.drawText(textToDraw, x, y, mPaint);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isTextModeOn) {
touch_start(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if (!isTextModeOn) {
touch_move(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (isTextModeOn) {
drawText((int) x, (int) y);
invalidate();
} else {
touch_up();
invalidate();
}
break;
}
return true;
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
invalidate();
} else {
}
// toast the user
}
public void onClickRedo() {
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
invalidate();
} else {
}
// toast the user
}
}
public void colorChanged(int color) {
// TODO Auto-generated method stub
lastColor = color;
drawView.colorChanged(lastColor);
}
class PathPoints {
private Path path;
// private Paint mPaint;
private int color;
private String textToDraw;
private boolean isTextToDraw;
private int x, y;
public PathPoints(Path path, int color, boolean isTextToDraw) {
this.path = path;
this.color = color;
this.isTextToDraw = isTextToDraw;
}
public PathPoints(int color, String textToDraw, boolean isTextToDraw,
int x, int y) {
this.color = color;
this.textToDraw = textToDraw;
this.isTextToDraw = isTextToDraw;
this.x = x;
this.y = y;
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public String getTextToDraw() {
return textToDraw;
}
public void setTextToDraw(String textToDraw) {
this.textToDraw = textToDraw;
}
public boolean isTextToDraw() {
return isTextToDraw;
}
public void setTextToDraw(boolean isTextToDraw) {
this.isTextToDraw = isTextToDraw;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
}
in your :
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
}
add these lines before canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.save();
canvas.drawColor(0xff000000);
hope it will help
Related
I am working in canvas related application and everything is working fine except clear all function.
I have used this code for creating canvas and it is also having a erase operation but it is erasing manually.
public class CharactersCanvas extends Activity {
public int width;
public int height;
public Arrays paths1;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;
private Paint circlePaint;
private Path circlePath;
static List<Integer> listFlag;
/* MyView mv; */
DrawingPanel dp;
AlertDialog dialog;
private ArrayList<Path> undonePaths = new ArrayList<Path>();
public ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<String> step = new ArrayList<String>();
FrameLayout frmLayout;
Canvas canvas;
protected static ImageView imageView;
private Integer frameIndex = 0;
public int res;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canvas_screen);
dp = new DrawingPanel(this);
frmLayout = (FrameLayout) findViewById(R.id.frameLayout1);
imageView=(ImageView) findViewById(R.id.imageView5);
frmLayout.addView(dp);
Bundle bundle = this.getIntent().getExtras();
res = bundle.getInt("resourseInt");
imageView.setImageResource(res);
frameIndex = (bundle != null && bundle.getInt("image") != 0) ? HomeScreen.characters.indexOf(bundle.getInt("image")) : frameIndex;
System.out.println(" Blank " + frameIndex);
frmLayout.setBackgroundResource((int)HomeScreen.characters.get(frameIndex));
/*
* if(){ dp.setBackgroundResource(R.drawable.atemplate); }
*/
((Button) findViewById(R.id.clear_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
if (paths != null)
paths.clear();
if(dp !=null)
dp.invalidate();
}
});
((Button) findViewById(R.id.next_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
if (frameIndex < (HomeScreen.characters.size() - 1)) {
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
System.out.println(" Size is "
+ HomeScreen.characters.size());
frmLayout
.setBackgroundResource((int) HomeScreen.characters
.get(frameIndex != HomeScreen.characters
.size() ? ++frameIndex
: frameIndex));
}
}
});
((Button) findViewById(R.id.previous_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (frameIndex >= 0) {
paths = new ArrayList<Path>();
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
frmLayout
.setBackgroundResource((int) HomeScreen.characters
.get(frameIndex == 0 ? frameIndex
: --frameIndex));
}
}
});
((Button) findViewById(R.id.letters_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MediaPlayer mPlayer = MediaPlayer.create(
CharactersCanvas.this, R.raw.one_sound);
mPlayer.start();
Intent intent = new Intent(getApplicationContext(),
CharactersGridView.class);
intent.putExtra("resourseInt", res);
// integerList is
// ArrayList<Integer>
startActivity(intent);
/*
* startActivity(new Intent(CharactersCanvas.this,
* CharactersGridView.class));
*/
}
});
((Button) findViewById(R.id.home_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MediaPlayer mPlayer = MediaPlayer.create(
CharactersCanvas.this, R.raw.one_sound);
mPlayer.start();
startActivity(new Intent(CharactersCanvas.this,
HomeScreen.class));
finish();
}
});
}
private Paint mPaint;
private MaskFilter mEmboss;
private MaskFilter mBlur;
public class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, circlePaint, outercirclePaint;
// private ArrayList<Path> undonePaths = new ArrayList<Path>();
private float xleft, xright, xtop, xbottom;
public DrawingPanel(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
circlePaint = new Paint();
mPaint = new Paint();
outercirclePaint = new Paint();
outercirclePaint.setAntiAlias(false);
circlePaint.setAntiAlias(false);
mPaint.setAntiAlias(false);
mPaint.setColor(0xFFFF0000);
outercirclePaint.setColor(0x44FFF000);
circlePaint.setColor(0xF57F35);
outercirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
outercirclePaint.setStrokeWidth(10);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
}
public void colorChanged(int color) {
mPaint.setColor(color);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
if (paths != null && paths.size() > 0) {
for (Path p : paths) {
canvas.drawPath(p, mPaint);
}
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
private void touch_start(float x, float y) {
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);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath = new Path();
paths.add(mPath);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// if (x <= cx+circleRadius+5 && x>= cx-circleRadius-5) {
// if (y<= cy+circleRadius+5 && cy>= cy-circleRadius-5){
// paths.clear();
// return true;
// }
// }
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;
}
}
}
I want to clear all the scribles using a single button .How to do this ?Any idea will be really usefull.
to clear the canvas's content you could draw a color,
canvas.drawColor(Color.TRANSPARENT)
for instance.
I want to clear all the drawn content in the canvas .I tried several ways and none was clicked for me yet.How to clear all the content in canvas android using clear button?
I have clear button to clear the content in canvas android.But I clearly did not know how to delete the content.I am having undo and redo button which is working fine except this clear button.Could some one tell me how to use this clear button and delete the content? My code is here.
public class MainActivity extends Activity {
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Path> paths = new ArrayList<Path>();
/*
* private Button alphabetsButton; private Button lettersButton; private
* Button clearButton;
*/
private FrameLayout frmLayout;
Canvas canvas;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frmLayout = (FrameLayout) findViewById(R.id.frameLayout);
final DrawingPanel dp = new DrawingPanel(MainActivity.this);
frmLayout.addView(dp);
/*
* alphabetsButton=(Button) findViewById(R.id.button1);
* lettersButton=(Button) findViewById(R.id.button2);
*
*
*
* alphabetsButton.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* stub startActivity(new Intent(MainActivity.this,Letters.class));
* finish(); } });
*/
((Button) findViewById(R.id.Clear)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
paths.clear();
}
});
((Button) findViewById(R.id.Undo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
dp.invalidate();
}
}
});
((Button) findViewById(R.id.Redo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
dp.invalidate();
}
}
});
}
class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, circlePaint, outercirclePaint;
private Bitmap mBitmap;
private int width;
private int height;
// private ArrayList<Path> undonePaths = new ArrayList<Path>();
private float xleft, xright, xtop, xbottom;
public DrawingPanel(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
circlePaint = new Paint();
mPaint = new Paint();
outercirclePaint = new Paint();
outercirclePaint.setAntiAlias(false);
circlePaint.setAntiAlias(false);
mPaint.setAntiAlias(false);
mPaint.setColor(0xFF000000);
outercirclePaint.setColor(0x44FFF000);
circlePaint.setColor(0xF57F35);
outercirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
outercirclePaint.setStrokeWidth(15);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
}
public void colorChanged(int color) {
mPaint.setColor(color);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
for (Path p : paths) {
canvas.drawPath(p, mPaint);
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
private void touch_start(float x, float y) {
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);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath = new Path();
paths.add(mPath);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// if (x <= cx+circleRadius+5 && x>= cx-circleRadius-5) {
// if (y<= cy+circleRadius+5 && cy>= cy-circleRadius-5){
// paths.clear();
// return true;
// }
// }
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;
}
}
}
may you should avoid to instantiate paths again before calling clear(), otherwise you'll call clear() on an empty ArrayList:
((Button) findViewById(R.id.Clear)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
}
});
Looks like the paths array list is persisting, try this code:
private ArrayList<Path> _graphics = new ArrayList<Path>()
#Override
public void onClick(View v) {
clear();
}
Bitmap mBitmap;
Paint mPaint;
Canvas mCanvas;
int width,height;
public void clear()
{
_graphics.removeAll(_graphics);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
path = new Path();
invalidate();
}
You can try this:
#Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
//paths.clear();
//.destroyDrawingCache();
mPath.reset();
dp.invalidate();
}
Am am trying to use a color picker change request with the SPen, I did not want to use the one they supplied I wanted to use my own.
here is my code below, the color picker comes up, but when i select a color it doesnt change the input of the PEN
public class numberTrace extends Activity implements OnInitListener, ColorPickerDialog.OnColorChangedListener {
private Paint mPaint;
Context mContext = null;
private RelativeLayout mCanvasContainer;
private SCanvasView mSCanvas;
private ImageView mEraserBtn;
private ImageView mNextBtn;
private ImageView mPenBtn;
public int currentNumber;
int[] myImageList = { R.drawable.numbers0, R.drawable.numbers1,
R.drawable.numbers2, R.drawable.numbers3, R.drawable.numbers4,
R.drawable.numbers5, R.drawable.numbers6, R.drawable.numbers7,
R.drawable.numbers8, R.drawable.numbers9 };
int cIndex = 0;
float speechRate = 1 / 4;
private TextToSpeech tts;
String[] speakNumbers = { "Number zero", "Number one", "Number two", "Number three", "Number four",
"Number five", "Number six", "Number seven", "Number eight", "Number nine" };
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.trace); // This is calling the layout in the
// main.xml file if I change the
// main.xml file name then I would
// Create the SCanvasView
tts = new TextToSpeech(this, this);
mContext = this;
mCanvasContainer = (RelativeLayout) findViewById(R.id.canvas_container);
mSCanvas = new SCanvasView(mContext);
mCanvasContainer.addView(mSCanvas);
mEraserBtn = (ImageView) findViewById(R.id.eraserBtn);
mNextBtn = (ImageView) findViewById(R.id.nextBtn);
mPenBtn = (ImageView) findViewById(R.id.penBtn);
mPaint = new Paint();
// on button click
// setting the background of the canvas
mSCanvas.setBackgroundResource(R.drawable.numbers0);
SCanvasInitializeListener mSCanvasListener = new SCanvasInitializeListener() {
public void onInitialized() {
// --------------------------------------------
// Start SCanvasView/CanvasView Task Here
// --------------------------------------------
// Application Identifier Setting
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
// Get the direction of contents(Canvas)
if (mSCanvas.getWidth() > mSCanvas.getHeight()) {
} else {
}
}
};
// ------------------------------------------------
// History Change
// ------------------------------------------------
HistoryUpdateListener mHistoryListener = new HistoryUpdateListener() {
public void onHistoryChanged(boolean undoable, boolean redoable) {
mNextBtn.setEnabled(undoable);
}
};
// ------------------------------------------------
// OnSettingStrokeChangeListener Listener
// ------------------------------------------------
SettingStrokeChangeListener mSettingStrokeChangeListener = new SettingStrokeChangeListener() {
public void onClearAll(boolean bClearAllCompleted) {
// If don't set eraser mode, then change to pen mode
// automatically.
if (bClearAllCompleted)
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_ERASER);
}
public void onEraserWidthChanged(int eraserWidth) {
}
public void onStrokeColorChanged(int strokeColor) {
}
public void onStrokeStyleChanged(int strokeStyle) {
}
public void onStrokeWidthChanged(int strokeWidth) {
}
public void onStrokeAlphaChanged(int strokeAlpha) {
}
};
mSCanvas.setSCanvasInitializeListener(mSCanvasListener);
mSCanvas.setSettingStrokeChangeListener(mSettingStrokeChangeListener);
mSCanvas.setColorPickerColorChangeListener(new ColorPickerColorChangeListener(){
#Override
public void onColorPickerColorChanged(int nColor) {
mPaint = new Paint();
int nCurMode = mSCanvas.getCanvasMode();
if(nCurMode==SCanvasConstants.SCANVAS_MODE_INPUT_PEN) {
SettingStrokeInfo strokeInfo = mSCanvas.getSettingViewStrokeInfo();
if(strokeInfo != null) {
strokeInfo.setStrokeColor(mPaint.getColor());
mSCanvas.setSettingViewStrokeInfo(strokeInfo);
}
}
}
});
mNextBtn.setOnClickListener(new OnClickListener() {
int i = 1;
#SuppressWarnings("deprecation")
public void onClick(View v) {
// TODO Auto-generated method stub
mSCanvas.clear();
mSCanvas.setBackgroundResource(myImageList[i]);// calling the
// array to mvoe
// to the next
// image
String speakNow = speakNumbers[cIndex];
tts.setSpeechRate(speechRate);
tts.speak(speakNow, TextToSpeech.QUEUE_FLUSH, null);
cIndex++;
cIndex %= speakNumbers.length;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
if (i >= myImageList.length) {
i = 0;
// erasing the drawings on the array
}
mNextBtn.setEnabled(mSCanvas.isUndoable());
}
});
mEraserBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int nBtnID = mEraserBtn.getId();
// If the mode is not changed, open the setting view. If the
// mode is same, close the setting view.
if (nBtnID == mEraserBtn.getId()) {
if (mSCanvas.getCanvasMode() == SCanvasConstants.SCANVAS_MODE_INPUT_ERASER) {
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_ERASER);
} else {
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_ERASER);
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_ERASER);
}
}
}
});
mPenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPaint = new Paint();
new ColorPickerDialog(numberTrace.this, numberTrace.this, mPaint.getColor()).show();
boolean bIsColorPickerMode = !mSCanvas.isColorPickerMode();
mSCanvas.setColorPickerMode(bIsColorPickerMode);
if (mPenBtn.equals(mPenBtn)) {
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
mSCanvas.getColorPickerColor(mPaint.getColor(), mPaint.getColor());
}
}
});
// Caution:
// Do NOT load file or start animation here because we don't know canvas
// size here.
// Start such SCanvasView/CanvasView Task at onInitialized() of
// SCanvasInitializeListener
mSCanvas.setSCanvasInitializeListener(mSCanvasListener);
mSCanvas.setHistoryUpdateListener(mHistoryListener);
mNextBtn.setEnabled(false);
// Caution:
// Do NOT load file or start animation here because we don't know canvas
// size here.
// Start such SCanvasView/CanvasView Task at onInitialized() of
// SCanvasInitializeListener
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_ERASER);
if (mSCanvas.getCanvasMode() == SCanvasConstants.SCANVAS_MODE_INPUT_PEN)
;
{
// Processed when the current mode of the SCanvasView is the Pen
// mode
}
}
public void onInit(int status) {
// TODO Auto-generated method stub
tts.setLanguage(Locale.US);
}
public void onDestroy() {
super.onDestroy();
tts.shutdown();
}
#Override
public void colorChanged(int color) {
// TODO Auto-generated method stub
SettingStrokeInfo strokeInfo = mSCanvas.getSettingViewStrokeInfo();
if(strokeInfo != null) {
strokeInfo.setStrokeColor(mPaint.getColor());
}
}
below is going to be the colorPicker class
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private OnColorChangedListener mListener;
private int mInitialColor;
private static class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
#Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0,
CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int floatToByte(float x) {
int n = java.lang.Math.round(x);
return n;
}
private int pinToByte(int n) {
if (n < 0) {
n = 0;
} else if (n > 255) {
n = 255;
}
return n;
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int)p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i+1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int rotateColor(int color, float rad) {
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir),
pinToByte(ig), pinToByte(ib));
}
private static final float PI = 3.1415926f;
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float)java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context,
OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
setContentView(new ColorPickerView(getContext(), l, mInitialColor));
setTitle("Pick a Color");
}
}
What and where do i need to change so that the SPen will write in the color chosen by the ColoPickerDialog class?
again everything works properly, just after choosing a color, the color writing stays black.
The way this was done was by Making a new settings View because as you can see above it was trying to get the settings view that was there, but I was not using the samsung settings view I was using my own color picking dialog. was trying to change the color of the stroke. The way this was done was by implementing the code below.
#Override
public void colorChanged(int color) {
// TODO Auto-generated method stub
mPaint.setColor(color);
final int pColor = mPaint.getColor();
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
int nCurMode = mSCanvas.getCanvasMode();
if(nCurMode==SCanvasConstants.SCANVAS_MODE_INPUT_PEN)
{
SettingStrokeInfo strokeInfo = new SettingStrokeInfo();
speakNow.setBackgroundColor(pColor);
strokeInfo.setStrokeColor(pColor);
mSCanvas.setSettingStrokeInfo(strokeInfo);
}
}
The Pen Button
mPenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mPenBtn.equals(mPenBtn)) {
mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
}
mPaint = new Paint();
new ColorPickerDialog(numberTrace.this, numberTrace.this, mPaint.getColor()).show();
}
});
That should help anyone else who is having the same problem.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Bitmap recycle with largeHeap enabled
hi am doing one app here i am displying images using bitmaps,that images is displaying well,but becz this class i am getting out of memory exception in another class.pls see once my code and how to solve this issue any suhhest me...
public class DesignofatozActivity extends Activity {
BitmapDrawable sounddrawable,erasedrawable,backdrwable,fwddrwable,captiondrwable;
Bitmap soundbitmap,eraseBitmap,backbitmap,fwdbitmap,captionbitmap;
bitmapOrg,bitmapOrg1,bitmapOrg2,bitmapOrg3,bitmapOrg4,bitmapOrg5,bitmapOrg6;
MyView myview;
File f;
ImageView d1,d2,d3,d4,d5,d6;
public boolean action=false;
RelativeLayout relativeLayout,layout,relativeLayout2;
Button c1,c2,c3,c4,c5,c6,c7,c8;
MediaPlayer player;
MediaPlayer mediay2;
ImageView horn;
float screenHeight,screenWidth,screendensity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setNoTitle();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
screendensity = displaymetrics.densityDpi;
Log.i("screenHeight",""+screenHeight);
Log.i("screenWidth",""+screenWidth);
Log.i("screendensity",""+screendensity);
setContentView(R.layout.line);
relativeLayout=(RelativeLayout)findViewById(R.id.relative);
relativeLayout.setBackgroundColor(Color.WHITE);
relativeLayout2=(RelativeLayout)findViewById(R.id.relative2);
RelativeLayout.LayoutParams layoutrel2= (RelativeLayout.LayoutParams) relativeLayout2.getLayoutParams();
layoutrel2.height=(int)(25*(screenHeight/600));
int toplay=(int)(90*(screenHeight/600));
layout=new RelativeLayout(this);
RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(0, toplay, 0,0);
layout.setLayoutParams(lp);
relativeLayout.addView(layout,lp);
int topmyvi=(int)(45*(screenHeight/600));
myview = new MyView(this);
myview.setId(004);
RelativeLayout.LayoutParams lp6 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
lp6.setMargins(0, topmyvi, 0,0);
relativeLayout.addView(myview,lp6);
ImageView I2=new ImageView(this);
if(captiondrwable!= null) {
captionbitmap.recycle();
captiondrwable= null;
}
captionbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.caption22_1));
captiondrwable = new BitmapDrawable(captionbitmap);
I2.setBackgroundDrawable(captiondrwable);
int left2=(int)(15*(screenWidth/1024));
int widthhh2=(int)(100*(screenWidth/1024));
int hifhtttt2=(int)(50*(screenHeight/600));
RelativeLayout.LayoutParams rlp2=new RelativeLayout.LayoutParams(widthhh2,hifhtttt2);
rlp2.setMargins(left2, topmyvi, 0, 0);
relativeLayout.addView(I2,rlp2);
ImageView b1=new ImageView(this);
if(erasedrawable!= null) {
eraseBitmap.recycle();
erasedrawable= null;
}
eraseBitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.eraser_501));
erasedrawable = new BitmapDrawable(eraseBitmap);
b1.setBackgroundDrawable(erasedrawable);
int leftb1=(int)(650*(screenWidth/1024));
int topb1=(int)(10*(screenHeight/600));
int widtb1=(int)(100*(screenWidth/1024));
int hightb1=(int)(100*(screenHeight/600));
RelativeLayout.LayoutParams rlp3=new RelativeLayout.LayoutParams(widtb1,hightb1);
rlp3.setMargins(leftb1, topb1, 0, 0);
relativeLayout.addView(b1,rlp3);
b1.setOnClickListener(new OnClickListener() {
// #Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
});
int lefth1=(int)(830*(screenWidth/1024));
int toph1=(int)(35*(screenHeight/600));
int width1=(int)(60*(screenWidth/1024));
int highth1=(int)(60*(screenHeight/600));
horn=new ImageView(this);
if(sounddrawable!= null) {
soundbitmap.recycle();
sounddrawable= null;
}
soundbitmap=BitmapFactory.decodeStream(getResources().openRawResource( R.drawable.horn));
sounddrawable = new BitmapDrawable(soundbitmap);
horn.setBackgroundDrawable(sounddrawable);
RelativeLayout.LayoutParams hn=new RelativeLayout.LayoutParams(width1,highth1);
hn.setMargins(lefth1,toph1,0,0);
relativeLayout.addView(horn,hn);
horn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediay2==null)
{
mediay2 = MediaPlayer.create(DesignofatozActivity.this, R.raw.hwprepsheets);
}
mediay2.start();
if(mediay2!=null)
{
}
}
});
ImageView next=(ImageView)findViewById(R.id.imv1a);
if(fwddrwable!= null) {
fwdbitmap.recycle();
fwddrwable= null;
}
fwdbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.next_50));
fwddrwable = new BitmapDrawable(fwdbitmap);
next.setBackgroundDrawable(fwddrwable);
RelativeLayout.LayoutParams layoutnxt= (RelativeLayout.LayoutParams) next.getLayoutParams();
layoutnxt.height=(int)(30*(screenHeight/600));
layoutnxt.width=(int)(50*(screenWidth/1024));
next.setOnClickListener(new OnClickListener() {
// #Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("next","next");
Intent i =new Intent(DesignofatozActivity.this,Dots.class);
startActivity(i);
}
});
ImageView back=(ImageView)findViewById(R.id.back);
if(backdrwable!= null) {
backbitmap.recycle();
backdrwable= null;
}
backbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.back1_50));
backdrwable = new BitmapDrawable(backbitmap);
back.setBackgroundDrawable(backdrwable);
RelativeLayout.LayoutParams layoutbak= (RelativeLayout.LayoutParams) back.getLayoutParams();
layoutbak.height=(int)(30*(screenHeight/600));
layoutbak.width=(int)(50*(screenWidth/1024));
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i =new Intent(DesignofatozActivity.this,Slantlines.class);
startActivity(i);
}
});
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
//mPaint.setColor(0xFFFF0000);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
}
private void setNoTitle() {
// TODO Auto-generated method stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
private Paint mPaint;
private Bitmap mBitmap;
public void colorChanged(int color) {
mPaint.setColor(color);
}
public class MyView extends View
{
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mBitmap != null) {
mBitmap.recycle();
mBitmap=null;
}
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.setBitmap(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
if(action)
{
invalidate();
}
Paint painto = new Paint();
painto.setAntiAlias(true);
painto.setStrokeWidth(3);
painto.setStyle(Paint.Style.FILL);
int leftx1=(int)(15*(screenWidth/1024));
int leftx2=(int)(1010*(screenWidth/1024));
int topy1=(int)(60*(screenHeight/600));
int topy2=(int)(530*(screenHeight/600));
canvas.drawLine(leftx1, topy1, leftx2, topy1, painto);
canvas.drawLine(leftx1, topy1, leftx1, topy2, painto);
canvas.drawLine(15, topy2, leftx2, topy2, painto);
canvas.drawLine(leftx2, topy1, leftx2, topy2, painto);
bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_4);
int leftorg=(int)(150*(screenWidth/1024));
int toporg=(int)(110*(screenHeight/600));
canvas.drawBitmap(bitmapOrg, leftorg, toporg, painto);
bitmapOrg.recycle();
bitmapOrg=null;
bitmapOrg1 = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_5);
int leftorg1=(int)(430*(screenWidth/1024));
int toporg1=(int)(130*(screenHeight/600));
canvas.drawBitmap(bitmapOrg1, leftorg1,toporg1, painto);
bitmapOrg1.recycle();
bitmapOrg1=null;
bitmapOrg2 = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_6);
int leftorg2=(int)(650*(screenWidth/1024));
canvas.drawBitmap(bitmapOrg2, leftorg2,toporg, painto);
bitmapOrg2.recycle();
bitmapOrg2=null;
bitmapOrg3 = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_1);
int leftorg3=(int)(170*(screenWidth/1024));
int toporg3=(int)(350*(screenHeight/600));
canvas.drawBitmap(bitmapOrg3, leftorg3,toporg3, painto);
bitmapOrg3.recycle();
bitmapOrg3=null;
bitmapOrg4 = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_3);
int leftorg4=(int)(680*(screenWidth/1024));
canvas.drawBitmap(bitmapOrg4, leftorg4,toporg3, painto);
bitmapOrg4.recycle();
bitmapOrg4=null;
bitmapOrg5 = BitmapFactory.decodeResource(getResources(),
R.drawable.circles1_2);
int leftorg5=(int)(400*(screenWidth/1024));
int toporg5=(int)(300*(screenHeight/600));
canvas.drawBitmap(bitmapOrg5, leftorg5,toporg5, painto);
bitmapOrg5.recycle();
bitmapOrg5=null;
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setColor(Color.BLACK);
paint1.setStrokeWidth(3);
paint1.setStyle(Paint.Style.FILL);
paint1.setTextSize(13);
canvas.drawText("Get ready to write place your pen on the dot and follow direction ", 120, 20, paint1);
canvas.drawText("indicated by the arrow . ", 120, 38, paint1);
Paint p = new Paint();
p.setAntiAlias(true);
p.setTextSize(120);
p.setColor(Color.LTGRAY);
Typeface font = Typeface.createFromAsset(getAssets(), "font/KINDTRG.TTF");
p.setTypeface(font);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
} private float mX, mY;
private final float TOUCH_TOLERANCE = 2;
private void touch_start(float x, float y) {
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);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
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;
}
}
public void clearAllResources() {
// Set related variables null
System.gc();
Runtime.getRuntime().gc();
}
#Override
protected void onPause() {
if (mediay2 != null){
mediay2.stop();
mediay2.release();
mediay2=null;
}
clearAllResources();
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.gc();
Runtime.getRuntime().gc();
unbindDrawables(findViewById(R.id.relative));
}
private void unbindDrawables(View view) {
// TODO Auto-generated method stub
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
You use memory heap more than gcc allowed size. You must use slaced bitmaps
or
+3.0 in manifest add application
android:largeHeap="true" to allocate more heap size.
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:largeHeap="true">...
Try This
After you get bitmap then recycle bitmap after use this will solve some issue.
Bitmap finalImage;
finalImage.recycle();
Or try in onResume()
System.gc();
I suggest you have a look at this thread: Strange out of memory issue while loading an image to a Bitmap object
This was answer on the thread:
public Bitmap readAssetsBitmap(String filename) throws IOException {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeStream(assets.open(filename), null, options);
if(bitmap == null) {
throw new IOException("File cannot be opened: It's value is null");
}
else {
return bitmap;
}
} catch (IOException e) {
throw new IOException("File cannot be opened: " + e.getMessage());
}
}
Remember to recycle bitmaps and set them to null once they have been used to ensure the get GCed.
Note: You shouldn't call System.gc();
I hope this helps.
I have developed an application which draws lines on the screen .I want to use different colors for the lines but all the lines are appearing in same color.
I have a color picker in my code to change the colors and i want to draw lines of different colors each time by selecting colors, but as of now since i am constructing lines and rendering it.When i choose initially red and draw a line, and then later select blue and draw a line , now the older line is also getting changed to blue instead of red, However i want the red to remain as red, and blue as such can any one help?
My code is given below
MyDemo.java:
public class MyDemo extends Activity implements
ColorPickerDialog.OnColorChangedListener {
private LinearLayout root;
private Button btnReset;
private Button btnPickColor;
public static int selectedColor = Color.BLACK;
MyImageView view;
private static final String COLOR_PREFERENCE_KEY = "color";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_demo);
root = (LinearLayout) findViewById(R.id.root);
btnReset = (Button) findViewById(R.id.reset);
btnPickColor = (Button) findViewById(R.id.pickColor);
final MyImageView view = new MyImageView(this);
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
root.addView(view);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.reset();
}
});
btnPickColor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// color picker class call
int color = PreferenceManager.getDefaultSharedPreferences(
MyDemo.this).getInt(COLOR_PREFERENCE_KEY, Color.WHITE);
new ColorPickerDialog(MyDemo.this, MyDemo.this, color).show();
}
});
}
public void colorChanged(int color) {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putInt(COLOR_PREFERENCE_KEY, color).commit();
selectedColor = color;
}
}
MyImageView.java:
public class MyImageView extends ImageView implements View.OnTouchListener {
private int id = -1;
private Path path;
private List<Path> paths = new ArrayList<Path>();
private List<PointF> points = new ArrayList<PointF>();
boolean multiTouch = false;
MyDemo demo;
public MyImageView(Context context) {
super(context);
this.setOnTouchListener(this);
Log.d("Constructor", " Control in constructor");
}
public void reset() {
paths.clear();
points.clear();
path = null;
id = -1;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int colorPicked = MyDemo.selectedColor;
if (colorPicked != Color.BLACK) {
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(colorPicked));
}
} else {
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(colorPicked));
}
}
private PointF copy(PointF p) {
PointF copy = new PointF();
copy.set(p);
return copy;
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
multiTouch = false;
id = event.getPointerId(0);
PointF p = getPoint(event, id);
path = new Path();
path.moveTo(p.x, p.y);
paths.add(path);
points.add(copy(p));
break;
case MotionEvent.ACTION_POINTER_DOWN:
multiTouch = true;
for (int i = 0; i < event.getPointerCount(); i++) {
int tId = event.getPointerId(i);
if (tId != id) {
points.add(getPoint(event, i));
}
}
break;
case MotionEvent.ACTION_MOVE:
if (!multiTouch) {
p = getPoint(event, id);
path.lineTo(p.x, p.y);
}
break;
}
invalidate();
return true;
}
private PointF getPoint(MotionEvent event, int i) {
int index = 0;
return new PointF(event.getX(index), event.getY(index));
}
public Paint createPen(int color) {
Paint pen = new Paint();
pen.setColor(color);
float width = 3;
pen.setStrokeWidth(width);
return pen;
}
}
ColorPickerDialog.java:
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private final OnColorChangedListener mListener;
private final int mInitialColor;
private static class ColorPickerView extends View {
private final Paint mPaint;
private final Paint mCenterPaint;
private final int[] mColors;
private final OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF,
0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 };
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
#Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0, CENTER_RADIUS
+ mCenterPaint.getStrokeWidth(), mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0)
return colors[0];
if (unit >= 1)
return colors[colors.length - 1];
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private static final float PI = 3.1415926f;
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float) java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / (2 * PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
layout.setPadding(10, 10, 10, 10);
layout.addView(new ColorPickerView(getContext(), l, mInitialColor),
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
setContentView(layout);
setTitle("Pick a Color");
}
}
I'm not sure but it seams a problem is in your onDraw method
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
You select a color first (it's the last color you picked) and then with a same color you draw each path.
I think that the solution for this could be to create array of colors which will contain color for every path you create and to pick corresponding color before you draw each path
try this, it will help you
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
int colorPicked = MainActivity.selectedColor;
paint1 = createPen(colorPicked);
for (Path p : paths){
canvas.drawPath(p, paint1);
paint1.setColor(colorPicked);
}
}
private Paint createPen(int color) {
// TODO Auto-generated method stub
paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setDither(true);
paint1.setStyle(Paint.Style.STROKE);
paint1.setStrokeJoin(Paint.Join.ROUND);
paint1.setStrokeCap(Paint.Cap.ROUND);
paint1.setStrokeWidth(3);
return paint1;
}