I have canvas drawing app. I successfully done integrating floodfill algorithm for filling color for finger drawing circle and rectangle area. My problem is after filling color on finger drawing circle when i used blur mask brush effect and drawing using finger by blur mask brush then whole blur mask brush drawing is repaint again and again. Here is my code:
public class DrawingView extends View {
private final Paint mDefaultPaint;
Bitmap mBitmap;
float x, y;
ProgressDialog pd;
LinearLayout drawing_layout;
private Canvas mLayerCanvas = new Canvas();
private Bitmap mLayerBitmap;
final Point p1 = new Point();
private Stack<DrawOp> mDrawOps = new Stack<>();
private Stack<DrawOp> mUndoOps = new Stack<>();
boolean isFill = false;
private SparseArray<DrawOp> mCurrentOps = new SparseArray<>(0);
public DrawingView(Context context) {
this(context, null, 0);
}
public DrawingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawingView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDefaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDefaultPaint.setStyle(Paint.Style.STROKE);
mDefaultPaint.setStrokeJoin(Paint.Join.ROUND);
mDefaultPaint.setStrokeCap(Paint.Cap.ROUND);
mDefaultPaint.setStrokeWidth(40);
mDefaultPaint.setColor(Color.GREEN);
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
setLayerType(LAYER_TYPE_SOFTWARE, null);
setSaveEnabled(true);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
final int pointerCount = MotionEventCompat.getPointerCount(event);
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN: {
if (isFill == true) {
int xx = (int) event.getX();
int yy = (int) event.getY();
Point pp = new Point(xx, yy);
/*Point pp = new Point();
pp.x = (int) event.getX();
pp.y = (int) event.getY();*/
final int sourceColor = mLayerBitmap.getPixel(xx, yy);
final int targetColor = mDefaultPaint.getColor();
new TheTask(mLayerBitmap, pp, sourceColor, targetColor)
.execute();
// JniBitmap.floodFill(mLayerBitmap, xx, yy, sourceColor,targetColor);
/* FloodFill f = new FloodFill();
f.floodFill(mLayerBitmap, pp, sourceColor, targetColor);*/
}
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
DrawOp current = new DrawOp(mDefaultPaint);
current.getPath().moveTo(event.getX(), event.getY());
mCurrentOps.put(id, current);
}
}
break;
case MotionEvent.ACTION_MOVE: {
if (isFill == false) {
final int id = MotionEventCompat.getPointerId(event, 0);
DrawOp current = mCurrentOps.get(id);
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++) {
x = event.getHistoricalX(h);
y = event.getHistoricalY(h);
current.getPath().lineTo(x, y);
}
x = MotionEventCompat.getX(event, 0);
y = MotionEventCompat.getY(event, 0);
current.getPath().lineTo(x, y);
}
}
break;
case MotionEvent.ACTION_UP: {
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
mDrawOps.push(mCurrentOps.get(id));
mCurrentOps.remove(id);
}
updateLayer();
}
break;
case MotionEvent.ACTION_CANCEL: {
for (int p = 0; p < pointerCount; p++) {
mCurrentOps.remove(MotionEventCompat.getPointerId(event, p));
}
updateLayer();
}
break;
default:
return false;
}
invalidate();
return true;
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
// this.bmp = bm;
mLayerBitmap = bm;
pd = new ProgressDialog(getContext());
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
pd.setMessage("Filling....");
pd.show();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill f = new FloodFill();
// mLayerBitmap = f.floodFill(bmp, pt, targetColor, replacementColor);
f.floodFill(mLayerBitmap, pt, targetColor, replacementColor);
// New Commented Algorithm
// f.FloodFill(mLayerBitmap, pt, targetColor, replacementColor);
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
invalidate();
isFill = false;
}
}
public void fillShapeColor(Bitmap mBitmap2) {
isFill = true;
}
public void setDrawing() {
isFill = false;
}
#Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
mLayerBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mLayerCanvas.setBitmap(mLayerBitmap);
updateLayer();
}
private void updateLayer() {
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode()) {
return;
}
canvas.drawBitmap(mLayerBitmap, 0, 0, null);
for (int i = 0; i < mCurrentOps.size(); i++) {
DrawOp current = mCurrentOps.valueAt(i);
if (current != null) {
current.draw(canvas);
}
}
}
public void operationClear() {
mDrawOps.clear();
mUndoOps.clear();
mCurrentOps.clear();
// To Clear Whole Canvas
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
updateLayer();
}
public void operationUndo() {
if (mDrawOps.size() > 0) {
mUndoOps.push(mDrawOps.pop());
updateLayer();
}
}
public void operationRedo() {
if (mUndoOps.size() > 0) {
mDrawOps.push(mUndoOps.pop());
updateLayer();
}
}
public void setPaintStrokeWidth(float widthPx) {
mDefaultPaint.setStrokeWidth(widthPx);
}
/*public float getPaintStrokeWidth(){
return mDefaultPaint.getStrokeWidth();
}*/
public void setPaintOpacity(int percent) {
int alphaValue = (int) Math.round(percent * (255.0 / 100.0));
mDefaultPaint.setColor(combineAlpha(mDefaultPaint.getColor(),
alphaValue));
}
/*public int getPaintOpacity(){
this.setPaintOpacity(50);
return mDefaultPaint.getColor();
}*/
public void setPaintColor(String color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(Color.parseColor(color),
mDefaultPaint.getAlpha()));
// mDefaultPaint.setColor(mDefaultPaint.getAlpha());
}
public void setPaintColor(int color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(color, mDefaultPaint.getAlpha()));
}
// New Created
public void setEraser(int color){
// mDefaultPaint.setAlpha(0xFF);
mDefaultPaint.setColor(color);
mDefaultPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setPaintMaskFilter(MaskFilter filter) {
mDefaultPaint.setMaskFilter(filter);
}
/*public MaskFilter getPaintMaskFilter(){
return mDefaultPaint.getMaskFilter();
}*/
public void setPaintShader(BitmapShader shader) {
mDefaultPaint.setShader(shader);
}
public void setPaintColorFilter(ColorFilter colorFilter) {
mDefaultPaint.setColorFilter(colorFilter);
}
private static int combineAlpha(int color, int alpha) {
return (color & 0x00FFFFFF) | ((alpha & 0xFF) << 24);
}
private static class DrawOp {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path mPath = new Path();
public DrawOp(Paint paint) {
reset(paint);
}
void reset(Paint paint) {
mPath.reset();
update(paint);
}
void update(Paint paint) {
mPaint.set(paint);
}
void draw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
}
public Path getPath() {
return mPath;
}
}
}
After lots of research i fond my problem and getting correct it. Below is my code.
if (isFloodFill) {
if (mZoomMode) {
return false;
} else {
final Point p = new Point();
float[] mTmpPoint1 = new float[2];
mTmpPoint1[0] = event.getX() - mPanX;
mTmpPoint1[1] = event.getY() - mPanY;
mZoomMatrixInv.mapPoints(mTmpPoint1);
p.x = (int) (mTmpPoint1[0]);
p.y = (int) (mTmpPoint1[1]);
System.out.println("--plotX mTmpPoint0: touch:" + p.x);
System.out.println("--plotY mTmpPoint0: touch:" + p.y);
this.mBitmap = getBitmap();
if (this.mBitmap != null) {
if(p.x > mBitmap.getWidth() || p.y > mBitmap.getHeight())
{
return false;
}
else
{
if(p.x >= 0 && p.y >= 0)
{
this.color = this.mBitmap.getPixel(p.x, p.y);
}
else
{
return false;
}
}
}
try {
// isFilling = false;
new FloodFillAlgo().execute(p);
return false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I am working on Android project in which I am cropping image in custom view and get that cropped image successfully. Now I want to edit that drawn shape or Move that shape as I want. I want to edit drawn shape by touching and dragging on line with perfect boundry.
Here is my Cropping
An i am getting Result like this
Now I want to move shape line on image OR Dragging line on image
Here is my code of Custom view
public class SomeView extends View implements OnTouchListener {
private Paint paint;
public static List<Point> points;
int DIST = 2;
boolean flgPathDraw ;//= true;
public Uri orignalUri;
float origianlheight=0.0f,originalwidth=0.0f,heightratio=0.0f,widthratio=0.0f;
public static int REQUEST_CODE=2;
Point mfirstpoint = null;
boolean bfirstpoint = false;
Point mlastpoint = null;
boolean cropflag=false;
Bitmap bitmap = null;//BitmapFactory.decodeResource(getResources(),R.drawable.bg_crop);
Context mContext;
public void setBitmap(Bitmap bmp,Uri uri){
orignalUri=uri;
points = new ArrayList<Point>();
setFocusable(true);
setFocusableInTouchMode(true);
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bmp.getHeight();
originalwidth=bmp.getWidth();
bitmap=bmp;
if (originalwidth > origianlheight) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
bmp = Bitmap.createBitmap(bmp, 0, 0,
bmp.getWidth(), bmp.getHeight(), matrix,
true);
}
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth()*widthratio),(int)(bmp.getHeight()*widthratio), true);
// bitmap=bmp;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
flgPathDraw = true;
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
cropflag=false;
}
public void clear(){
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
flgPathDraw = true;
cropflag=false;
invalidate();
}
public SomeView(Context c) {
super(c);
mContext = c;
setFocusable(true);
setFocusableInTouchMode(true);
/* DisplayMetrics metrics = c.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bitmap.getHeight();
originalwidth=bitmap.getWidth();
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=Bitmap.createScaledBitmap(bitmap, (int)(originalwidth*widthratio),(int)(origianlheight*widthratio), true);*/
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
// flgPathDraw = true;
cropflag=false;
}
public SomeView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setFocusable(true);
setFocusableInTouchMode(true);
/* DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bitmap.getHeight();
originalwidth=bitmap.getWidth();
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=Bitmap.createScaledBitmap(bitmap, (int)(originalwidth*widthratio),(int)(origianlheight*widthratio), true);*/
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
// flgPathDraw = true;
cropflag=false;
}
public void onDraw(Canvas canvas) {
if(bitmap!=null)
canvas.drawBitmap(bitmap, 0, 0,paint);
Path path = new Path();
boolean first = true;
for (int i = 0; i < points.size(); i += 2) {
Point point = points.get(i);
if (first) {
first = false;
path.moveTo(point.x, point.y);
} else if (i < points.size() - 1) {
Point next = points.get(i + 1);
path.quadTo(point.x, point.y, next.x, next.y);
} else {
mlastpoint = points.get(i);
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
#Override
public boolean onTouch(View view, MotionEvent event) {
// if(event.getAction() != MotionEvent.ACTION_DOWN)
// return super.onTouchEvent(event);
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
if (flgPathDraw) {
if (bfirstpoint) {
if (comparepoint(mfirstpoint, point)) {
// points.add(point);
points.add(mfirstpoint);
flgPathDraw = false;
// showcropdialog();
cropflag=true;
} else {
points.add(point);
}
} else {
points.add(point);
}
if (!(bfirstpoint)) {
mfirstpoint = point;
bfirstpoint = true;
}
}
invalidate();
Log.e("Hi ==>", "Size: " + point.x + " " + point.y);
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("Action up*******~~~~~~~>>>>", "called");
mlastpoint = point;
if (flgPathDraw) {
if (points.size() > 12) {
if (!comparepoint(mfirstpoint, mlastpoint)) {
flgPathDraw = false;
points.add(mfirstpoint);
// showcropdialog();
cropflag=true;
}
}
}
}
return true;
}
private boolean comparepoint(Point first, Point current) {
int left_range_x = (int) (current.x - 3);
int left_range_y = (int) (current.y - 3);
int right_range_x = (int) (current.x + 3);
int right_range_y = (int) (current.y + 3);
if ((left_range_x < first.x && first.x < right_range_x)
&& (left_range_y < first.y && first.y < right_range_y)) {
if (points.size() < 10) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public void fillinPartofPath() {
Point point = new Point();
point.x = points.get(0).x;
point.y = points.get(0).y;
points.add(point);
invalidate();
}
public void resetView() {
points.clear();
paint.setColor(Color.WHITE);
paint.setStyle(Style.STROKE);
flgPathDraw = true;
invalidate();
}
/* private void showcropdialog() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
// bfirstpoint = false;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
mContext.startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", false);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
mContext.startActivity(intent);
bfirstpoint = false;
// resetView();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Do you Want to save Crop or Non-crop image?")
.setPositiveButton("Crop", dialogClickListener)
.setNegativeButton("Non-crop", dialogClickListener).show()
.setCancelable(false);
}*/
public void Crop(){
if(cropflag){
new SwichTask().execute();
}
}
ProgressDialog progressDialog;
private void showProgressDialog() {
if (progressDialog != null)
progressDialog.show();
else
progressDialog = ProgressDialog.show(mContext, null,"Cropping");
}
private void dismissProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
private class SwichTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
#Override
protected Void doInBackground(Void... params) {
System.out.println("Switch Activity is call");
Intent intent;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
((Activity)mContext).startActivityForResult(intent,REQUEST_CODE);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dismissProgressDialog();
}
}
}
Thank you
I have canvas drawing app. I successfully done integrating floodfill algorithm for filling color for finger drawing circle and rectangle area. My problem is after filling color on finger drawing circle when i used blur mask brush effect and drawing using finger by blur mask brush then whole blur mask brush drawing is repaint again and again. Here is my code:
public class DrawingView extends View {
private final Paint mDefaultPaint;
Bitmap mBitmap;
float x, y;
ProgressDialog pd;
LinearLayout drawing_layout;
private Canvas mLayerCanvas = new Canvas();
private Bitmap mLayerBitmap;
final Point p1 = new Point();
private Stack<DrawOp> mDrawOps = new Stack<>();
private Stack<DrawOp> mUndoOps = new Stack<>();
boolean isFill = false;
private SparseArray<DrawOp> mCurrentOps = new SparseArray<>(0);
public DrawingView(Context context) {
this(context, null, 0);
}
public DrawingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawingView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDefaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDefaultPaint.setStyle(Paint.Style.STROKE);
mDefaultPaint.setStrokeJoin(Paint.Join.ROUND);
mDefaultPaint.setStrokeCap(Paint.Cap.ROUND);
mDefaultPaint.setStrokeWidth(40);
mDefaultPaint.setColor(Color.GREEN);
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
setLayerType(LAYER_TYPE_SOFTWARE, null);
setSaveEnabled(true);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
final int pointerCount = MotionEventCompat.getPointerCount(event);
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN: {
if (isFill == true) {
int xx = (int) event.getX();
int yy = (int) event.getY();
Point pp = new Point(xx, yy);
/*Point pp = new Point();
pp.x = (int) event.getX();
pp.y = (int) event.getY();*/
final int sourceColor = mLayerBitmap.getPixel(xx, yy);
final int targetColor = mDefaultPaint.getColor();
new TheTask(mLayerBitmap, pp, sourceColor, targetColor)
.execute();
// JniBitmap.floodFill(mLayerBitmap, xx, yy, sourceColor,targetColor);
/* FloodFill f = new FloodFill();
f.floodFill(mLayerBitmap, pp, sourceColor, targetColor);*/
}
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
DrawOp current = new DrawOp(mDefaultPaint);
current.getPath().moveTo(event.getX(), event.getY());
mCurrentOps.put(id, current);
}
}
break;
case MotionEvent.ACTION_MOVE: {
if (isFill == false) {
final int id = MotionEventCompat.getPointerId(event, 0);
DrawOp current = mCurrentOps.get(id);
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++) {
x = event.getHistoricalX(h);
y = event.getHistoricalY(h);
current.getPath().lineTo(x, y);
}
x = MotionEventCompat.getX(event, 0);
y = MotionEventCompat.getY(event, 0);
current.getPath().lineTo(x, y);
}
}
break;
case MotionEvent.ACTION_UP: {
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
mDrawOps.push(mCurrentOps.get(id));
mCurrentOps.remove(id);
}
updateLayer();
}
break;
case MotionEvent.ACTION_CANCEL: {
for (int p = 0; p < pointerCount; p++) {
mCurrentOps.remove(MotionEventCompat.getPointerId(event, p));
}
updateLayer();
}
break;
default:
return false;
}
invalidate();
return true;
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
// this.bmp = bm;
mLayerBitmap = bm;
pd = new ProgressDialog(getContext());
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
pd.setMessage("Filling....");
pd.show();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill f = new FloodFill();
// mLayerBitmap = f.floodFill(bmp, pt, targetColor, replacementColor);
f.floodFill(mLayerBitmap, pt, targetColor, replacementColor);
// New Commented Algorithm
// f.FloodFill(mLayerBitmap, pt, targetColor, replacementColor);
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
invalidate();
isFill = false;
}
}
public void fillShapeColor(Bitmap mBitmap2) {
isFill = true;
}
public void setDrawing() {
isFill = false;
}
#Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
mLayerBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mLayerCanvas.setBitmap(mLayerBitmap);
updateLayer();
}
private void updateLayer() {
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode()) {
return;
}
canvas.drawBitmap(mLayerBitmap, 0, 0, null);
for (int i = 0; i < mCurrentOps.size(); i++) {
DrawOp current = mCurrentOps.valueAt(i);
if (current != null) {
current.draw(canvas);
}
}
}
public void operationClear() {
mDrawOps.clear();
mUndoOps.clear();
mCurrentOps.clear();
// To Clear Whole Canvas
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
updateLayer();
}
public void operationUndo() {
if (mDrawOps.size() > 0) {
mUndoOps.push(mDrawOps.pop());
updateLayer();
}
}
public void operationRedo() {
if (mUndoOps.size() > 0) {
mDrawOps.push(mUndoOps.pop());
updateLayer();
}
}
public void setPaintStrokeWidth(float widthPx) {
mDefaultPaint.setStrokeWidth(widthPx);
}
/*public float getPaintStrokeWidth(){
return mDefaultPaint.getStrokeWidth();
}*/
public void setPaintOpacity(int percent) {
int alphaValue = (int) Math.round(percent * (255.0 / 100.0));
mDefaultPaint.setColor(combineAlpha(mDefaultPaint.getColor(),
alphaValue));
}
/*public int getPaintOpacity(){
this.setPaintOpacity(50);
return mDefaultPaint.getColor();
}*/
public void setPaintColor(String color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(Color.parseColor(color),
mDefaultPaint.getAlpha()));
// mDefaultPaint.setColor(mDefaultPaint.getAlpha());
}
public void setPaintColor(int color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(color, mDefaultPaint.getAlpha()));
}
// New Created
public void setEraser(int color){
// mDefaultPaint.setAlpha(0xFF);
mDefaultPaint.setColor(color);
mDefaultPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setPaintMaskFilter(MaskFilter filter) {
mDefaultPaint.setMaskFilter(filter);
}
/*public MaskFilter getPaintMaskFilter(){
return mDefaultPaint.getMaskFilter();
}*/
public void setPaintShader(BitmapShader shader) {
mDefaultPaint.setShader(shader);
}
public void setPaintColorFilter(ColorFilter colorFilter) {
mDefaultPaint.setColorFilter(colorFilter);
}
private static int combineAlpha(int color, int alpha) {
return (color & 0x00FFFFFF) | ((alpha & 0xFF) << 24);
}
private static class DrawOp {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path mPath = new Path();
public DrawOp(Paint paint) {
reset(paint);
}
void reset(Paint paint) {
mPath.reset();
update(paint);
}
void update(Paint paint) {
mPaint.set(paint);
}
void draw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
}
public Path getPath() {
return mPath;
}
}
}
I have canvas drawing app. I successfully done integrating floodfill algorithm for filling color for finger drawing circle and rectangle area by finger drawing shapes. My problem is after filling color for created shapes by finger, filled color is gone when drawing line on canvas.
public class DrawingView extends View {
private final Paint mDefaultPaint;
private final Paint mFloodPaint = new Paint();
Bitmap mBitmap;
float x, y;
ProgressDialog pd;
LinearLayout drawing_layout;
private Canvas mLayerCanvas = new Canvas();
private Bitmap mLayerBitmap;
final Point p1 = new Point();
private Stack<DrawOp> mDrawOps = new Stack<>();
private Stack<DrawOp> mUndoOps = new Stack<>();
boolean isFill;/* = false;*/
private SparseArray<DrawOp> mCurrentOps = new SparseArray<>(0);
public DrawingView(Context context) {
this(context, null, 0);
}
public DrawingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawingView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDefaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDefaultPaint.setStyle(Paint.Style.STROKE);
mDefaultPaint.setStrokeJoin(Paint.Join.ROUND);
mDefaultPaint.setStrokeCap(Paint.Cap.ROUND);
mDefaultPaint.setStrokeWidth(40);
mDefaultPaint.setColor(Color.GREEN);
/*mFloodPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mFloodPaint.setStyle(Paint.Style.STROKE);
mFloodPaint.setStrokeJoin(Paint.Join.ROUND);
mFloodPaint.setStrokeCap(Paint.Cap.ROUND);
mFloodPaint.setStrokeWidth(40);
mFloodPaint.setColor(Color.GREEN);*/
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
setLayerType(LAYER_TYPE_SOFTWARE, null);
setSaveEnabled(true);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
final int pointerCount = MotionEventCompat.getPointerCount(event);
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN: {
if (isFill == true) {
int xx = (int) event.getX();
int yy = (int) event.getY();
Point pp = new Point(xx, yy);
/*Point pp = new Point();
pp.x = (int) event.getX();
pp.y = (int) event.getY();*/
final int sourceColor = mLayerBitmap.getPixel(xx, yy);
final int targetColor = mDefaultPaint.getColor();
// final int targetColor = mFloodPaint.getColor();
new TheTask(mLayerBitmap, pp, sourceColor, targetColor)
.execute();
// JniBitmap.floodFill(mLayerBitmap, xx, yy, sourceColor,targetColor);
/* FloodFill f = new FloodFill();
f.floodFill(mLayerBitmap, pp, sourceColor, targetColor);*/
}
else if(isFill == false){
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
DrawOp current = new DrawOp(mDefaultPaint);
current.getPath().moveTo(event.getX(), event.getY());
mCurrentOps.put(id, current);
}
}
}
break;
case MotionEvent.ACTION_MOVE: {
if (isFill == false) {
final int id = MotionEventCompat.getPointerId(event, 0);
DrawOp current = mCurrentOps.get(id);
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++) {
x = event.getHistoricalX(h);
y = event.getHistoricalY(h);
current.getPath().lineTo(x, y);
}
x = MotionEventCompat.getX(event, 0);
y = MotionEventCompat.getY(event, 0);
current.getPath().lineTo(x, y);
}
}
break;
case MotionEvent.ACTION_UP: {
if(isFill == false){
// mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
mDrawOps.push(mCurrentOps.get(id));
mCurrentOps.remove(id);
}
updateLayer();
}
}
/* else{
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
mDrawOps.push(mCurrentOps.get(id));
mCurrentOps.remove(id);
}
}*/
// }
break;
case MotionEvent.ACTION_CANCEL: {
if(isFill == false){
for (int p = 0; p < pointerCount; p++) {
mCurrentOps.remove(MotionEventCompat.getPointerId(event, p));
}
updateLayer();
}
}
break;
default:
return false;
}
invalidate();
return true;
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
// this.bmp = bm;
mLayerBitmap = bm;
pd = new ProgressDialog(getContext());
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
pd.setMessage("Filling....");
pd.show();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill f = new FloodFill();
// mLayerBitmap = f.floodFill(bmp, pt, targetColor, replacementColor);
f.floodFill(mLayerBitmap, pt, targetColor, replacementColor);
// New Commented Algorithm
// f.FloodFill(mLayerBitmap, pt, targetColor, replacementColor);
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
invalidate();
isFill = false;
}
}
public void fillShapeColor(Bitmap mBitmap2) {
isFill = true;
}
/*public void fillShapeColor() {
isFill = true;
}*/
public void setDrawing() {
isFill = false;
}
#Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
mLayerBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mLayerCanvas.setBitmap(mLayerBitmap);
updateLayer();
}
/* private void updateDLayer(){
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
invalidate();
}*/
private void updateLayer() {
/* isFill=false;
if(isFill==false){
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
else{
System.out.println("Not using mLayerCanvas.drawColor()");
}*/
// mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
// this.getPaintStrokeWidth();
// this.getPaintMaskFilter();
/* if(isFill == false){
// this.getPaintOpacity();
mLayerCanvas.save();
// mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
mLayerCanvas.restore();
}*/
/*mDefaultPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
mLayerCanvas.drawPaint(mDefaultPaint);
mDefaultPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
mLayerCanvas.drawPaint(mDefaultPaint);*/
/* if(isFill==false){
mLayerCanvas.save();
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
mLayerCanvas.restore();
invalidate();
}
else{
mLayerCanvas.save();
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
mLayerCanvas.restore();
}*/
/*DrawOp dr = new DrawOp(mDefaultPaint);
if(dr.getPath().isEmpty()){
// isFill = true;
isFill = false;
}
else{
isFill=true;
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
}*/
if(isFill == false){
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode()) {
return;
}
/*int w = canvas.getWidth();
int h = canvas.getHeight();
canvas.drawRect(0,0,w,h, mDefaultPaint);*/
canvas.drawBitmap(mLayerBitmap, 0, 0, null);
for (int i = 0; i < mCurrentOps.size(); i++) {
DrawOp current = mCurrentOps.valueAt(i);
if (current != null) {
current.draw(canvas);
}
}
}
public void operationClear() {
mDrawOps.clear();
mUndoOps.clear();
mCurrentOps.clear();
// To Clear Whole Canvas
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
updateLayer();
}
public void operationUndo() {
if (mDrawOps.size() > 0) {
mUndoOps.push(mDrawOps.pop());
updateLayer();
}
}
public void operationRedo() {
if (mUndoOps.size() > 0) {
mDrawOps.push(mUndoOps.pop());
updateLayer();
}
}
public void setPaintStrokeWidth(float widthPx) {
mDefaultPaint.setStrokeWidth(widthPx);
// mFloodPaint.setStrokeWidth(widthPx);
}
/*public float getPaintStrokeWidth(){
return mDefaultPaint.getStrokeWidth();
}*/
public void setPaintOpacity(int percent) {
int alphaValue = (int) Math.round(percent * (255.0 / 100.0));
mDefaultPaint.setColor(combineAlpha(mDefaultPaint.getColor(),
alphaValue));
// mFloodPaint.setColor(combineAlpha(mFloodPaint.getColor(),
// alphaValue));
}
/*public int getPaintOpacity(){
this.setPaintOpacity(50);
return mDefaultPaint.getColor();
}*/
public void setPaintColor(String color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(Color.parseColor(color),
mDefaultPaint.getAlpha()));
// mDefaultPaint.setColor(mDefaultPaint.getAlpha());
mFloodPaint.setXfermode(null);
mFloodPaint.setColor(combineAlpha(Color.parseColor(color),
mFloodPaint.getAlpha()));
}
public void setPaintColor(int color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(color, mDefaultPaint.getAlpha()));
mFloodPaint.setXfermode(null);
mFloodPaint.setColor(combineAlpha(color, mFloodPaint.getAlpha()));
}
// New Created
public void setEraser(int color){
// mDefaultPaint.setAlpha(0xFF);
mDefaultPaint.setColor(color);
mDefaultPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setPaintMaskFilter(MaskFilter filter) {
mDefaultPaint.setMaskFilter(filter);
// mFloodPaint.setMaskFilter(filter);
}
/*public MaskFilter getPaintMaskFilter(){
return mDefaultPaint.getMaskFilter();
}*/
public void setPaintShader(BitmapShader shader) {
mDefaultPaint.setShader(shader);
// mFloodPaint.setShader(shader);
}
public void setPaintColorFilter(ColorFilter colorFilter) {
mDefaultPaint.setColorFilter(colorFilter);
// mFloodPaint.setColorFilter(colorFilter);
}
private static int combineAlpha(int color, int alpha) {
return (color & 0x00FFFFFF) | ((alpha & 0xFF) << 24);
}
private static class DrawOp {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path mPath = new Path();
public DrawOp(Paint paint) {
reset(paint);
}
void reset(Paint paint) {
mPath.reset();
update(paint);
}
void update(Paint paint) {
mPaint.set(paint);
}
void draw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
}
public Path getPath() {
return mPath;
}
}
public void setFillColor(boolean flag){
this.isFill = flag;
}
}
update your updateLayer() method like below:
private void updateLayer() {
/*if(isFill == false){
mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
}*/
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
drawOp.draw(mCanvas);
}
}
invalidate();
}
How to get the all points? I want to store all those points in csv file format. One more thing, I have normalized points still not getting all those points!
DrawingView-class:
public class DrawingView extends View {
static Path drawPath;
private Paint drawPaint, canvasPaint;
static int paintColor = Color.BLACK;
private float STROKE_WIDTH = 10f;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
private boolean erase = false;
Context context;
FileWriter fw;
private static int mX;
private static int mY;
private static ArrayList<Integer> xPoints = new ArrayList<Integer>();
private static ArrayList<Integer> yPoints = new ArrayList<Integer>();
Integer xInt[]={};
Integer yInt[]={};
int x[];
int y[];
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
private void setupDrawing() {
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(STROKE_WIDTH);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
#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);
drawCanvas = new Canvas(canvasBitmap);
}
private void touch_start(int x, int y) {
drawPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(int x, int y) throws IOException {
drawPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
arrayPopulate(x, y);
}
private void touch_up(int x, int y) {
drawPath.lineTo(x, y);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
}
public void csvHeader(String s1, String s2) throws IOException {
// TODO Auto-generated method stub
String line = String.format("%s,%s\n", s1, s2);
fw.write(line);
}
#SuppressLint("DefaultLocale")
private void csvData(int x, int y) throws IOException {
// TODO Auto-generated method stub
String line = String.format("%d,%d\n", x, y);
fw.write(line);
}
private void arrayPopulate(int xCord, int yCord) {
xPoints.add(xCord / 10);
yPoints.add(yCord / 10);
xInt=xPoints.toArray(xInt);
yInt=yPoints.toArray(yInt);
}
public void makeFile(Integer[] xArr,Integer yArr[]) {
x=RemoveDuplicate.removed(xArr);
y=RemoveDuplicate.removed(yArr);
try {
File f = new File(Environment.getExternalStorageDirectory(),
"Notes");
if (!f.exists()) {
f.mkdirs();
}
File file = new File(f, "test.txt");
fw = new FileWriter(file);
csvHeader("X", "Y");
for (int i=0;i<x.length;i++) {
int xvalue=x[i];
int yvalue=y[i];
csvData(xvalue, yvalue);
fw.flush();
}
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent e) {
canvasPaint.setColor(paintColor);
int x = (int) e.getX();
int y = (int) e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
arrayPopulate(x, y);
break;
case MotionEvent.ACTION_MOVE:
try {
touch_move(x, y);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
touch_up(x, y);
makeFile(xInt, yInt);
break;
default:
return false;
}
invalidate();
return true;
}
public void setErase(boolean isErase) throws IOException
{
erase = isErase;
drawPaint = new Paint();
if (erase) {
setupDrawing();
canvasBitmap.eraseColor(Color.TRANSPARENT);
fw.close();
} else {
setupDrawing();
}
}
}
RemoveDuplicate-class:
public class RemoveDuplicate {
public static int[] removed(Integer[] points)
{
int[] input = new int[points.length];
for (int i = 0; i < points.length; i++) {
input[i]=points[i].intValue();
}
int current = input[0];
boolean found = false;
for (int i = 0; i < input.length; i++) {
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
current = input[i];
found = false;
}
}
return input ;
}
}
hi am doing one app for all devices using display metrics.. in 2.2 version,here i am using custom view for drawing function.some times its working well.i learn many times that time i am getting outof memory exception.in emulater i incresed heap size that time its working all fine.how to increse heap size in older versions,and whats i did wrong in my code i didnt understand can u any one have idea suggest me.....
public class A extends Activity {
BitmapDrawable sounddrawable,erasedrawable,backdrwable,fwddrwable,captiondrwable,strtdrwable,stpdrwable;
Bitmap soundbitmap,eraseBitmap,backbitmap,fwdbitmap,captionbitmap,strtbitmap,stpbitmap;
MyView myview;
GlobalClass global;
RelativeLayout.LayoutParams lp6;
SampleView sampleview;
ImageView img;
MediaPlayer nextsound;
boolean count=true;
MediaPlayer mediay2;
ImageView horn;
String user;
int username;
Bundle b;
RelativeLayout relativeLayout,relativeLayout1;
ImageView strtbtn,stpbtn,erase;
float screenHeight,screenWidth,screendensity;
public boolean action=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
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.alh);
int topsampl=(int)(80*(screenHeight/600));
global=(GlobalClass)this.getApplication();
if(sampleview==null)
{
sampleview=new SampleView(this);
}
lp6 = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
sampleview.setLayoutParams(lp6);
lp6.setMargins(0,topsampl , 0, 0);
relativeLayout=(RelativeLayout)findViewById(R.id.relative);
RelativeLayout.LayoutParams layoutrel= (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();
layoutrel.height=(int)(600*(screenHeight/600));
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreateAAAAAAAAAA", "memoryClass:" + Integer.toString(memoryClass));
relativeLayout1=(RelativeLayout)findViewById(R.id.relative2);
RelativeLayout.LayoutParams layoutre2= (RelativeLayout.LayoutParams) relativeLayout1.getLayoutParams();
layoutre2.height=(int)(35*(screenHeight/600));
int left=(int)(15*(screenWidth/1024));
int top=(int)(50*(screenHeight/600));
int widthhh=(int)(80*(screenWidth/1024));
int hifhtttt=(int)(50*(screenHeight/600));
ImageView I2=new ImageView(this);
if(captiondrwable!= null) {
captionbitmap.recycle();
captiondrwable= null;
}
if(captiondrwable== null) {
captionbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.practise));
}
captiondrwable = new BitmapDrawable(captionbitmap);
I2.setBackgroundDrawable(captiondrwable);
RelativeLayout.LayoutParams rlp=new RelativeLayout.LayoutParams(widthhh,hifhtttt);
rlp.setMargins(left, top, 0, 0);
relativeLayout.addView(I2,rlp);
b =getIntent().getExtras();
user=b.getString("k1");
username=Integer.parseInt(user);
Log.i("username..........",""+username);
Log.i("user..........",""+user);
ImageView next=(ImageView)findViewById(R.id.imv1a);
if(fwddrwable!= null) {
fwdbitmap.recycle();
fwddrwable= null;
}
if(fwddrwable== null) {
fwdbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.next_5011));
}
fwddrwable = new BitmapDrawable(fwdbitmap);
next.setBackgroundDrawable(fwddrwable);
RelativeLayout.LayoutParams layoutnext= (RelativeLayout.LayoutParams) next.getLayoutParams();
layoutnext.height=(int)(35*(screenHeight/600));
layoutnext.width=(int)(50*(screenWidth/1024));
next.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("next","..........");
Intent i =new Intent(A.this,Smallletera.class);
i.putExtra("k1", user);
startActivity(i);
if(nextsound==null)
{
nextsound = MediaPlayer.create(getApplicationContext(),R.raw.chime_up);
}
nextsound.start();
if(nextsound!=null)
{
}
}
});
ImageView back=(ImageView)findViewById(R.id.back);
if(backdrwable!= null) {
backbitmap.recycle();
backdrwable= null;
}
if(backdrwable== null) {
backbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.back1_50));
}
backdrwable = new BitmapDrawable(backbitmap);
back.setBackgroundDrawable(backdrwable);
RelativeLayout.LayoutParams layoutback= (RelativeLayout.LayoutParams) back.getLayoutParams();
layoutback.height=(int)(35*(screenHeight/600));
layoutback.width=(int)(50*(screenWidth/1024));
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("next","..........");
Intent i =new Intent(A.this,HWindex.class);
startActivity(i);
}
});
if(myview==null)
{
myview = new MyView(this);
}
myview.setBackgroundColor(Color.WHITE);
myview.setId(004);
lp6 = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
lp6.setMargins(0,top , 0, 0);
relativeLayout.addView(myview,lp6);
horn=new ImageView(this);
if(sounddrawable!= null) {
soundbitmap.recycle();
sounddrawable= null;
}
if(sounddrawable== null) {
soundbitmap=BitmapFactory.decodeStream(getResources().openRawResource( R.drawable.horn));
}
sounddrawable = new BitmapDrawable(soundbitmap);
horn.setBackgroundDrawable(sounddrawable);
int left1=(int)(830*(screenWidth/1024));
int top1=(int)(50*(screenHeight/600));
int widthhh1=(int)(60*(screenWidth/1024));
int hifhtttt1=(int)(60*(screenHeight/600));
RelativeLayout.LayoutParams hn=new RelativeLayout.LayoutParams(widthhh1,hifhtttt1);
hn.setMargins(left1,top1,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(A.this, R.raw.uppercaseinstructions);
}
mediay2.start();
if(mediay2!=null)
{
}
}
});
strtbtn = new ImageView(this);
if(strtdrwable!= null) {
strtbitmap.recycle();
strtdrwable= null;
}
if(strtdrwable== null) {
strtbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.play_50));
}
strtdrwable = new BitmapDrawable(strtbitmap);
strtbtn.setBackgroundDrawable(strtdrwable);
int left2=(int)(520*(screenWidth/1024));
int top2=(int)(60*(screenHeight/600));
int widthhh2=(int)(40*(screenWidth/1024));
int hifhtttt2=(int)(40*(screenHeight/600));
strtbtn.setId(1);
RelativeLayout.LayoutParams rlp1=new RelativeLayout.LayoutParams(widthhh2,hifhtttt2);
rlp1.setMargins(left2, top2, 0, 0);
relativeLayout.addView(strtbtn,rlp1);
strtbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count==true)
{
Log.i("---------dfgdf-----","--------");
relativeLayout.addView(sampleview,lp6);
count=false;
}
}
});
stpbtn=new ImageView(this);
if(stpdrwable!= null) {
stpbitmap.recycle();
stpdrwable= null;
}
if(stpdrwable== null) {
stpbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.stop_50));
}
stpdrwable = new BitmapDrawable(stpbitmap);
stpbtn.setBackgroundDrawable(stpdrwable);
int left3=(int)(570*(screenWidth/1024));
int top3=(int)(60*(screenHeight/600));
stpbtn.setId(2);
RelativeLayout.LayoutParams rlp2=new RelativeLayout.LayoutParams(widthhh2,hifhtttt2);
rlp2.setMargins(left3, top3,0,0);
relativeLayout.addView(stpbtn,rlp2);
stpbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count==false)
{
Log.i("------stop--------","--");
relativeLayout.removeView(sampleview);
count=true;
}
}
});
erase=new ImageView(this);
if(erasedrawable!= null) {
eraseBitmap.recycle();
erasedrawable= null;
}
if(erasedrawable== null) {
eraseBitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.eraser_50));
}
erasedrawable = new BitmapDrawable(eraseBitmap);
erase.setBackgroundDrawable(erasedrawable);
int left4=(int)(620*(screenWidth/1024));
int top4=(int)(50*(screenHeight/600));
int widthhh4=(int)(60*(screenWidth/1024));
int hifhtttt4=(int)(60*(screenHeight/600));
RelativeLayout.LayoutParams rlp4=new RelativeLayout.LayoutParams(widthhh4,hifhtttt4);
rlp4.setMargins(left4, top4, 0, 0);
relativeLayout.addView(erase,rlp4);
erase.setOnClickListener(new OnClickListener() {
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();
}
}
}) ;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
}
private Paint mPaint;
public void colorChanged(int color) {
mPaint.setColor(color);
}
private Bitmap mBitmap;
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;
}
if(mBitmap==null)
{
mBitmap= Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
}
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
Paint painto = new Paint();
painto.setAntiAlias(true);
painto.setColor(getResources().getColor(R.color.magnata));
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);
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setColor(Color.BLACK);
paint1.setStrokeWidth(3);
paint1.setStyle(Paint.Style.FILL);
paint1.setTextSize(15);
canvas.drawText("Practice writing the letter by tracing it over and over again . ", 110, 40, paint1);
Paint p1=new Paint();
p1.setColor(getResources().getColor(R.color.bcolor));
if(screendensity==160)
{
p1.setTextSize(630);
}
if(screendensity==240)
{
p1.setTextSize(650);
}
p1.setAntiAlias(true);
Typeface font = Typeface.createFromAsset(getAssets(), "font/KINDTRG.TTF");
p1.setTypeface(font);
float lefta=(int)(270*(screenWidth/1024));
float lefta1=(int)(290*(screenWidth/1024));
float lefta2=(int)(320*(screenWidth/1024));
float lefta3=(int)(340*(screenWidth/1024));
float lefta4=(int)(350*(screenWidth/1024));
float lefta5=(int)(370*(screenWidth/1024));
float lefta6=(int)(335*(screenWidth/1024));
float lefta7=(int)(300*(screenWidth/1024));
float lefta8=(int)(265*(screenWidth/1024));
float topa=(int)(505*(screenHeight/600));
float topa1=(int)(520*(screenHeight/600));
float topa2=(int)(510*(screenHeight/600));
float topa3=(int)(500*(screenHeight/600));
float topa4=(int)(495*(screenHeight/600));
float topa5=(int)(490*(screenHeight/600));
if(username==1)
{
canvas.drawText("A", lefta, topa, p1);
}
if(username==2)
{
canvas.drawText("B", lefta, topa, p1);
}
if(username==3)
{
canvas.drawText("C", lefta, topa, p1);
}
if(username==4)
{
canvas.drawText("D", lefta, topa1, p1);
}
if(username==5)
{
canvas.drawText("E", lefta3, topa1, p1);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
if(action)
{
invalidate();
}
} private float mX, mY;
private 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);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
public void clearAllResources() {
// Set related variables null
System.gc();
Runtime.getRuntime().gc();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.relative));
System.gc();
}
private void unbindDrawables(View view) {
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();
}
}
protected void onstop() {
clearAllResources();
super.onStop();
}
class SampleView extends View {
java.io.InputStream is;
private Movie mMovie;
private long mMovieStart;
private byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public SampleView(Context context) {
super(context);
setFocusable(true);
if(global.bugcount==1)
{
is = context.getResources().openRawResource(R.drawable.a);
}
if(global.bugcount==2)
{
is = context.getResources().openRawResource(R.drawable.b);
}
if(global.bugcount==3)
{
is = context.getResources().openRawResource(R.drawable.c);
}
if(global.bugcount==4)
{
is = context.getResources().openRawResource(R.drawable.d);
}
if(global.bugcount==5)
{
is = context.getResources().openRawResource(R.drawable.e);
}
if (true) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
#Override protected void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setAntiAlias(true);
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(),
getHeight() - mMovie.height());
invalidate();
}
}
}
#Override
protected void onPause() {
if (mediay2 != null){
mediay2.stop();
mediay2.release();
mediay2=null;
}
if(nextsound != null) {
if (nextsound.isPlaying()) {
nextsound.stop();
}
nextsound.release();
nextsound = null;
}
clearAllResources();
super.onPause();
}
}
i am getting exception in inside myview on sizechnage()....
try to load your images configuring and using BitmapsOptions
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html