Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get images on Canvas from device

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 166
    Comment on it

    Step 1:- Create a custom CanvasView class that must extend View class and includes below function.

     

    1) Declare the required variables in CanvasView class

        private Drawable mImage;
        // width and height of original image
        private float mImageWidth;
        private float mImageHeight;
        // when image is scaled, we use this to calculate the bounds of the image
        private int mImageWidthScaled;
        private int mImageHeightScaled;
        public float mPosX = 0;
        public float mPosY = 0;

    2)   Create constructor that will get the get the bitmap as:-
     

     public CanvasView(Context context BitmapDrawable image, Bitmap bitmap, int count, float scaleFactor)
       {
          super(context);
          this.mImage = image;
          this.mBitmap = bitmap;
          mImageWidth = mBitmap.getWidth();
          mImageHeight = mBitmap.getHeight();
          this.mScaleFactor = scaleFactor;
          isImageRotate = true;
          mScaleDetector = new ScaleGestureDetector(context, new ScaleListener())
        }

    3)  onDraw():-

    canvas.restore();
    canvas.drawColor(Color.TRANSPARENT);
     /* this draw the bitmap to the canvas that we have got from constructor */
    canvas.drawBitmap(mBitmap, mPosX, mPosY, new Paint()); 
    canvas.save();

    4) Override the onTouchEvent function

    This will help to move the selected image on the canvas
    We have set the mPosX=0, mPosY= 0 so that when one select the image it will appear on the top
    and with the help of we can re-position the canvas.

    @Override
    public boolean onTouchEvent(MotionEvent event) {
       mScaleDetector.onTouchEvent(event);
       boolean intercept = false;
       switch (event.getAction() & MotionEvent.ACTION_MASK) {
       case MotionEvent.ACTION_DOWN:
             mLastTouchX = event.getX();
             mLastTouchY = event.getY();
             mActivePointerId = event.getPointerId(0);;
          if(((mLastTouchX >= mPosX)&&(mLastTouchX <= mPosX + mImageWidthScaled) 
      && (mLastTouchY >= mPosY) && (mLastTouchY <= mPosY +mImageHeightScaled))) /*it checks the moving position and actual position */
            {
                     intercept = true;
                     mSelected = true;
                     mStyle.setmCurrentView(mNumberView);
             } 
          else {
                 System.out.println("nothing doing");
               }
       break;
       case MotionEvent.ACTION_MOVE:
           final int pointerIndex = event.findPointerIndex(mActivePointerId);
           final float x = event.getX(pointerIndex);
           final float y = event.getY(pointerIndex);
          if (!mScaleDetector.isInProgress()) {
            final float dx = x - mLastTouchX;
            final float dy = y - mLastTouchY;
                    mPosX += dx;
                        mPosY += dy;
                        // Invalidate to request a redraw
                        invalidate();
                    } else {
                    }
                    // Remember this touch position for the next move event
                    mLastTouchX = x;
                    mLastTouchY = y;
                    break;
    
                default:
                    //return defaultResult;
            }
            return intercept;
        }

    Step 2:- Create a class ScaleListner that willl extend ScaleGestureDetector

    This sets the scale factor for the image drawn on the canvas.

      private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
            @Override
            public boolean onScale(ScaleGestureDetector detector) {
                mScaleFactor *= detector.getScaleFactor();
                mScaleFactor = Math.max(0.2f, Math.min(mScaleFactor, 5f));
                invalidate();
                return true;
            }
        }


    Step 3:- on your main activity  includes below function.

    Select the image from gallery and onActivityResult add given lines of code:-
    1) This will get the image from device.
    2) Creates a new canvas dynamically, store image the arraylist of type "View".
    3) All the canvas created will be placed on the Relative Layout of your xml .

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GALLERY_PIC_REQUEST) {
          try {
           Uri selectedImage = data.getData();
           Bitmap bitmap = decodeUriAsBitmap(selectedImage);
           InputStream is;
           is = getContentResolver().openInputStream(selectedImage);
           int mDstWidth = 250; // this will be the size of image on the canvas
           int mDstHeight = 250;
    Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap,mDstWidth,mDstHeight,true);
           bitmap.recycle();
    CanvasView newView = new CanvasView(Drawing.this, Drawing.this, new BitmapDrawable(scaledBitmap), scaledBitmap, mViewsCount, 1f);
      newView.setImageLocation(selectedImage.getPath());
      newView.setClickable(true);
      newView.setmSelected(true);
      mViewsArray.add(newView);//add above created view on the arraylist of type View
      RelativeLayout layout = (RelativeLayout) findViewById(R.id.canvas_container);
      CanvasView canvasView = (CanvasView) findViewById(R.id.view_drawing);
      layout.addView(mViewsArray.get(mViewsCount));
      newView.invalidate();
       mViewsCount += 1;
     } catch (FileNotFoundException e) {
     } catch (NullPointerException e) {
    }}
    }

    Note:- Each time you select the image , it will create a new canvas hold it on the RelativeLayout say
    "canvas_container"

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: