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
Related
I am trying draw on the image. Now I am using following class.
public class DrawingPaint extends View implements View.OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, mBitmapPaint;
public ArrayList<PathPoints> paths = new ArrayList<PathPoints>();
private ArrayList<PathPoints> undonePaths = new ArrayList<PathPoints>();
private Bitmap mBitmap;
private int color;
private int x, y;
private String textToDraw = null;
private boolean isTextModeOn = false;
int lastColor = 0xFFFF0000;
static final float STROKE_WIDTH = 15f;
public DrawingPaint(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.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(STROKE_WIDTH);
mPaint.setTextSize(30);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();*/
}
public void colorChanged(int color) {
this.color = color;
mPaint.setColor(color);
}
public void setColor(int color) {
mPaint = new Paint();
this.color = color;
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(STROKE_WIDTH);
mPaint.setTextSize(30);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// mBitmap = AddReportItemActivity.mPhoto;
mBitmap = CustomGalleryHandler.getmInstance().getBitmapSend();
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;
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(new PathPoints(mPath, color, false));
}
private void drawText(int x, int 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() {
try {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
invalidate();
} else {
}
} catch (Exception e) {
e.toString();
}
}
public void onClickRedo() {
try {
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
invalidate();
} else {
}
} catch (Exception e) {
e.toString();
}
}
}
The following method is used in Activity extended class
public class GalleryImageFullScreen extends Activity implements View.OnClickListener {
private ImageView mFullScreenImage;
private ImageView /*mWhiteColor,*//* mGreenColor, mSkyBlueColor, mYellowColor, mRedColor, mBlackColor,*/ mUndoIcon,
mPaintImageSave, mPaintImageDelete, mRedoIcon;
RoundedImageView mWhiteColor, mGreenColor, mSkyBlueColor, mYellowColor, mRedColor, mBlackColor;
// private Signature mSignature;
private RelativeLayout mDrawLayout;
private DrawingPaint mDrawViewSignature;
private AlertDialog mAlertDialog = null;
Bitmap bitmapss;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery_fullscreen);
super.onCreate(savedInstanceState);
mUndoIcon =(ImageView)findViewById(R.id.erase_icon);
mFullScreenImage=(ImageView)findViewById(R.id.img_fullscreen);
mDrawLayout=(RelativeLayout)findViewById(R.id.img_fullscreen_layout);
mPaintImageSave=(ImageView)findViewById(R.id.paint_img_save);
mPaintImageDelete=(ImageView)findViewById(R.id.paint_img_delete);
mRedoIcon=(ImageView)findViewById(R.id.img_redo);
mWhiteColor.setOnClickListener(this);
mGreenColor.setOnClickListener(this);
mSkyBlueColor.setOnClickListener(this);
mYellowColor.setOnClickListener(this);
mRedColor.setOnClickListener(this);
mBlackColor.setOnClickListener(this);
mUndoIcon.setOnClickListener(this);
mPaintImageSave.setOnClickListener(this);
mPaintImageDelete.setOnClickListener(this);
mRedoIcon.setOnClickListener(this);
// mSignature = new Signature(GalleryImageFullScreen.this, null);
try {
Intent i=getIntent();
Bitmap image = null;
image = BitmapFactory.decodeFile(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().setBitmapSend(image);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
mDrawLayout.getLayoutParams().width = imageWidth;
mDrawLayout.getLayoutParams().height = imageHeight;
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(imageWidth,imageHeight);
// mDrawLayout.setLayoutParams(layout_description);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(imageWidth,
imageHeight, Bitmap.Config.ARGB_8888);
mDrawViewSignature = new DrawingPaint(GalleryImageFullScreen.this/*, lastColor*/);
mDrawViewSignature.setDrawingCacheEnabled(true);
mDrawViewSignature.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
mDrawViewSignature.layout(0, 0, mDrawViewSignature.getMeasuredWidth(),
mDrawViewSignature.getMeasuredHeight());
mDrawViewSignature.buildDrawingCache(true);
Canvas canvas = new Canvas(mSignatureBitmapImage);
Drawable bgDrawable = mDrawLayout.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
mDrawLayout.draw(canvas);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
mSignatureBitmapImage.compress(Bitmap.CompressFormat.PNG, 50, bs);
}
catch (Exception e)
{
Logger.d("", "" + e.toString());
}
mDrawViewSignature.setColor(getResources().getColor(R.color.black));
mDrawLayout.addView(mDrawViewSignature);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.paint_img_save:
try {
Bitmap editedImage = Bitmap.createBitmap(mDrawViewSignature
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, mDrawViewSignature.getWidth(), mDrawViewSignature.getHeight(),
true);
if(editedImage!=null) {
final Bitmap finalEditedImage = editedImage;
mAlertDialog = Alerts.getInstance().createConfirmationDialog(this, this.getResources().getString(R.string.painting_image_save), new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bitmap editedImage = Bitmap.createBitmap(mDrawViewSignature
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, mDrawViewSignature.getWidth(), mDrawViewSignature.getHeight(),
true);*/
//saveImageToInternalStorage(finalEditedImage);
storeImage(finalEditedImage);
PreferenceForCustomCamera.getInstance().setEditedURL(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
callToGalleyActivity();
mAlertDialog.dismiss();
}
});
mAlertDialog.show();
}
}
catch (Exception e)
{
Logger.d("paint_img_save",""+e.toString());
}
break;
case R.id.paint_img_delete:
try {
if (!PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen().equals("") && !PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen().equals("null")) {
mAlertDialog = Alerts.getInstance().createConfirmationDialog(this, this.getResources().getString(R.string.painting_image_path_delete), new View.OnClickListener() {
#Override
public void onClick(View v) {
// DatabaseHelper.getInstance().deleteParticularVideoPath(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().deleteParticularImages(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().deleteParticularImageFromInternalStorage(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
callToGalleyActivity();
mAlertDialog.dismiss();
}
});
}
mAlertDialog.show();
}
catch (Exception e)
{
Logger.d("paint_img_delete",""+e.toString());
}
break;
case R.id.img_redo:
mDrawViewSignature.onClickRedo();
break;
}
}
private void saveImageToInternalStorage(Bitmap finalBitmap) {
try {
File myDir = new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
myDir.mkdirs();
Logger.d("ListOfPhoto",""+myDir.getAbsolutePath());
Logger.d("ListOfPhotoRename",""+PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
for(File files: myDir.listFiles())
{
Logger.d("ListOfPhoto",""+files.getAbsolutePath());
Logger.d("ListOfPhotoRename",""+PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
}
Picasso.with(getApplicationContext()).load(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen()).skipMemoryCache();
/*Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + "3680" + ".png";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}*/
try {
if(myDir.exists())
{
myDir.delete();
}
FileOutputStream out = new FileOutputStream(myDir);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e)
{
Logger.d("saveImageToInternalStorage",""+e.toString());
}
}
private void storeImage(Bitmap image) {
File pictureFile = new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
if (pictureFile.exists()) {
pictureFile.delete();
}
//clearImageDiskCache();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Logger.d("GalleryImage", "File not found: " + e.getMessage());
} catch (IOException e) {
Logger.d("GalleryImage", "Error accessing file: " + e.getMessage());
}
}
public boolean clearImageDiskCache() {
File cache = new File(getApplicationContext().getCacheDir(), "picasso-cache");
if (cache.exists() && cache.isDirectory()) {
return deleteDir(cache);
}
return false;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
The following code used in my xml for draw.
<RelativeLayout
android:id="#+id/img_fullscreen_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edit_components_bar"
android:layout_centerHorizontal="true">
<ImageView
android:id="#+id/img_fullscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
It is working fine when I use Landscape images. But when I use Portrait image, image getting stretched. Please let me know how to make the canvas fit to the image.
Thanks in advance
I alter this code:
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, imageWidth, imageHeight);
RectF outRect = new RectF(0, 0, imageWidth-10, imageHeight-10);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(image,0,0,imageWidth,
imageHeight, m,true);
I used this code also. But Not working:
Matrix m = mFullScreenImage.getImageMatrix();
RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
RectF viewRect = new RectF(0, 0, mFullScreenImage.getWidth(), mFullScreenImage.getHeight());
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(image,0,0,imageWidth,
imageHeight, m,true);
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();
}
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();
}
}
}
I want to erase my bitmap but I don't want to erase background image. When I try to erase is white and it draw very hard in frames.
this is my MainActivity code
private final String tag = "MainActivity";
private ImageView eraser;
private Button btnChooseImage;
private ImageButton btnClear, btnSave, btnShare, btnCamera;
private DrawingView drawingView;
private static final int SELECT_PHOTO = 100;
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
setContentView(R.layout.activity_main);
drawingView = (DrawingView) findViewById(R.id.drawing);
btnChooseImage = (Button) findViewById(R.id.btnChooseImage);
btnChooseImage.setOnClickListener(this);
btnClear = (ImageButton) findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
btnSave = (ImageButton) findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
btnShare = (ImageButton) findViewById(R.id.btnShare);
btnShare.setOnClickListener(this);
btnCamera = (ImageButton) findViewById(R.id.btnCamera);
btnCamera.setOnClickListener(this);
eraser = (ImageView) findViewById(R.id.eraser);
eraser.setOnClickListener(this);
}
}
#SuppressLint("NewApi") #Override
public void onClick(View v) {
if (v == eraser) {
if (drawingView.isEraserActive()) {
drawingView.deactivateEraser();
eraser.setImageResource(R.drawable.eraser);
} else {
drawingView.activateEraser();
eraser.setImageResource(R.drawable.pencil);
}
} else if (v == btnClear) {
drawingView.reset();
drawingView.setBackground(null);
} else if (v == btnSave) {
saveImage();
} else if (v == btnCamera) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else if (v == btnShare) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(saveImage().getAbsolutePath())); //"file:///sdcard/temporary_file.jpg"
startActivity(Intent.createChooser(share, "Share Image"));
} else if (v == btnChooseImage) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
public File saveImage() {
drawingView.setDrawingCacheEnabled(true);
Bitmap bm = drawingView.getDrawingCache();
File fPath = Environment.getExternalStorageDirectory();
File f = null;
f = new File(fPath, UUID.randomUUID().toString() + ".png");
try {
FileOutputStream strm = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 80, strm);
strm.close();
Toast.makeText(getApplicationContext(), "Image is saved successfully.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
return f;
}
#SuppressLint("NewApi") #SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
if(Build.VERSION.SDK_INT >= 16)
{
drawingView.setBackground(ob);
}else {
drawingView.setBackgroundDrawable(ob);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
case CAMERA_REQUEST:
if (resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
BitmapDrawable ob = new BitmapDrawable(getResources(), photo);
if(Build.VERSION.SDK_INT >= 16)
{
drawingView.setBackground(ob);
}else {
drawingView.setBackgroundDrawable(ob);
}
}
}
}
}
and here is the DrawingView code
private Canvas m_Canvas;
private Path m_Path;
private Paint m_Paint;
private ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();
private ArrayList<Pair<Path, Paint>> undonePaths = new ArrayList<Pair<Path, Paint>>();
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0.001f;
private boolean isEraserActive = false;
public DrawingView(Context context, AttributeSet attr) {
super(context, attr);
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
this.setOnTouchListener(this);
onCanvasInitialization();
}
public void onCanvasInitialization() {
m_Paint = new Paint();
m_Paint.setAntiAlias(true);
m_Paint.setDither(true);
m_Paint.setColor(Color.parseColor("#000000"));
m_Paint.setStyle(Paint.Style.STROKE);
m_Paint.setStrokeJoin(Paint.Join.ROUND);
m_Paint.setStrokeCap(Paint.Cap.ROUND);
m_Paint.setStrokeWidth(2);
m_Canvas = new Canvas();
m_Path = new Path();
Paint newPaint = new Paint(m_Paint);
paths.add(new Pair<Path, Paint>(m_Path, newPaint));
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
public boolean onTouch(View arg0, 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;
}
#Override
protected void onDraw(Canvas canvas) {
for (Pair<Path, Paint> p : paths) {
canvas.drawPath(p.first, p.second);
}
}
private void touch_start(float x, float y) {
if (isEraserActive) {
m_Paint.setColor(Color.WHITE);
m_Paint.setStrokeWidth(10);
Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
paths.add(new Pair<Path, Paint>(m_Path, newPaint));
} else {
m_Paint.setColor(Color.BLACK);
m_Paint.setStrokeWidth(2);
Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
paths.add(new Pair<Path, Paint>(m_Path, newPaint));
}
m_Path.reset();
m_Path.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) {
m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
m_Path.lineTo(mX, mY);
// commit the path to our offscreen
m_Canvas.drawPath(m_Path, m_Paint);
// kill this so we don't double draw
m_Path = new Path();
Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
paths.add(new Pair<Path, Paint>(m_Path, newPaint));
}
public void activateEraser()
{
isEraserActive = true;
}
public void deactivateEraser()
{
isEraserActive = false;
}
public boolean isEraserActive()
{
return isEraserActive;
}
public void reset()
{
paths.clear();
invalidate();
}
}
I wanted to erase the drawing view without changing the background image which is imported from gallery
make one function in your View class and clear all list views you have saved before and redraw the view like:
public void clearDrawing()
{
paths.clear();
invalidate();
}
invalidate() whill refresh the view. Call this method from your view object on click event in activity. Hope it will help.