Rectangle 27 2

according your requirement you have 2 use one of the android game framework you can find so many game engine check this thread or you can use andengine one of the best 2D game engine in that you can find many example code.

for your requirement just follow the PinchZoomExample from here

hi.. I have a same problem: I'm drawing and pasting image on canvas. Problem is when I zoom in/out or Drag the canvas, then I don't get the correct position of the canvas. Like if i've touched at 100,100 it might give me 256,450.. Plz guide me to solve it. I want correct cordinates after draging or scaling the canvas.

android canvas draw circles and get touch events - Stack Overflow

android touch zoom shape android-canvas
Rectangle 27 2

public boolean onTouchEvent(MotionEvent e)
        {
            int xpos=(int) e.getX();
            int ypos=(int) e.getY();
            switch (e.getAction())
            {
            case MotionEvent.ACTION_DOWN:
             Log.d("DEBUG", "On touch (down)" + String.valueOf(xpos) + String.valueOf(ypos));
            case MotionEvent.ACTION_UP:
            Log.d("DEBUG", "On touch (up)" + String.valueOf(xpos) + String.valueOf(ypos));
            case MotionEvent.ACTION_MOVE:
            Log.d("DEBUG", "On touch (move)" + String.valueOf(xpos) + String.valueOf(ypos));
            break;
        }
        return true;

    }

Then override the draw method

@Override
  public void draw(Canvas canvas) {
   super.draw(canvas);
   }

To make a line go straight up try

canvas.drawLine(xpos, ypos, xpos, getHeight() , new Paint());

Get height should be your screen's height (Since your drawing a line straight up)

int xpos,ypos = 0;

To the the top of your code (but within the class declaration)

For drawling a between the circles you would need to get the first circles x,y position on touch then set the drawLine method with them, so something like:

currentCircleXpos, lastCircleXpos = 0; //you would set these in the onDraw method when the circle get's drawn.
currentCircleYpos, lastCircleypos = 0;


canvas.drawLine(currentCircleXpos, currentCircleYpos, lastCircleXpos, lastCircleYpos , new Paint());
for (int y = 0; y < rows; y++)
    {
        for (int x = 0; x < cols; x++)
        {
            canvas.drawCircle((x + 1) * xStep, (y + 1) * yStep, 20, pDot);
             currentCircleXpos = x;
              currentCircleYpos = y; //gets the circle that is being drawn's location
        if (y == 0)
        {
            //canvas.drawLine((x + 1) * xStep, yStep, (x + 1) * xStep, rows * yStep, pDot);
        }                   
    }

    //canvas.drawLine(xStep, (y + 1) * yStep, cols * xStep, (y + 1) * yStep, pDot);
}

and those lines were between 1st circle to last circle horizontally and vertically now I was trying to display line between only two circles after occurrence of touch event.

You could use the same code but change the drawLine method, I'll update again to give you a rough idea.

Please check code now. Without tapping on screen It shows a small line on my device's upper left corner of screen.

How to get Touch Location on Screen (Android) - Stack Overflow

android android-canvas ontouchevent
Rectangle 27 7

tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw

here one simple class to draw line using canvas as show below.

public class TestLineView extends View {

    private Paint paint;
    private PointF startPoint, endPoint;
    private boolean isDrawing;

    public TestLineView(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        if(isDrawing)
        {
            canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startPoint = new PointF(event.getX(), event.getY());
                endPoint = new PointF();
                isDrawing = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    isDrawing = false;
                    invalidate();
                }
                break;
            default:
                break;
        }
        return true;
    }
}

How about free drawing? And the line to draw as you move your finger?

drawing - Draw in Canvas by finger, Android - Stack Overflow

android drawing touch android-canvas
Rectangle 27 7

tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw

here one simple class to draw line using canvas as show below.

public class TestLineView extends View {

    private Paint paint;
    private PointF startPoint, endPoint;
    private boolean isDrawing;

    public TestLineView(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        if(isDrawing)
        {
            canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startPoint = new PointF(event.getX(), event.getY());
                endPoint = new PointF();
                isDrawing = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    isDrawing = false;
                    invalidate();
                }
                break;
            default:
                break;
        }
        return true;
    }
}

How about free drawing? And the line to draw as you move your finger?

drawing - Draw in Canvas by finger, Android - Stack Overflow

android drawing touch android-canvas
Rectangle 27 1

Here's some example code to get you started. Each time the user touches, a new Line is created and added to a list of Lines.

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DrawLineView drawLineView = new DrawLineView(this);
    setContentView(drawLineView);
  }
}
public class DrawLineView extends View {

  List<Line> lines;
  Paint black;

  public DrawLineView(Context context) {
    super(context);

    // sets up a new list of Lines
    lines = new ArrayList<>(); 

    black = new Paint();
    black.setColor(Color.BLACK);
    black.setStrokeWidth(5);
  }

  @Override
  public void onDraw(Canvas canvas) {
    // for each of your Lines, draw them on the canvas
    for (Line line : lines) { 
      canvas.drawLine(line.xStart, line.yStart, line.xEnd, line.yEnd, black);
    }

    invalidate();
  }


  @Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {

      case MotionEvent.ACTION_DOWN:
        Line line = new Line(event.getX(), event.getY(), event.getX(), event.getY());
        lines.add(line);
        break;

      case MotionEvent.ACTION_MOVE:
        lines.get(lines.size() - 1).xEnd = event.getX();
        lines.get(lines.size() - 1).yEnd = event.getY();
        break;
    }
    return true;
  }

  class Line {
    public float xStart;
    public float yStart;
    public float xEnd;
    public float yEnd;

    public Line(float xStart, float yStart, float xEnd, float yEnd) {
      this.xStart = xStart;
      this.yStart = yStart;
      this.xEnd = xEnd;
      this.yEnd = yEnd;
    }
  }
}

tnx for your answer, but i am very Elementary , i dont underestand anything from ebove code , if is posible solve my problem with my own code, tnx

Sure. The problem with your code is that every time the user touches, the app overwrites the values of sX, sY, eX, and eY. The reason my code works is because every time I touch the screen, I create four new variables (which are stored inside my Line class), xStart, yStart, xEnd, yEnd and I add these to a List of values. This way, I don't overwrite the previous values. You need to create a List of values and every time the user touches you must add an entry to this List.

Tnx very much , i underestand what is problem , but what about this link? This is exactly like my code(except upTouch) and work corectly

android - End Canvas with touch up - Stack Overflow

android canvas graphic
Rectangle 27 1

package com.kWh360.image.editing;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class DrawingPanel extends View implements OnTouchListener {

    private Canvas mCanvas;
    private Path mPath;
    private Paint mPaint, mBitmapPaint;
    private ArrayList<PathPoints> paths = new ArrayList<PathPoints>();
    private ArrayList<PathPoints> undonePaths = new ArrayList<PathPoints>();
    private Bitmap mBitmap;
    private int color;
    public int SSL = Color.WHITE;
    private int x, y;
    private int strockWidth = 3;

    private String textToDraw = null;
    public static boolean isTextModeOn = false;

    int mWidth, mHeight;

    public DrawingPanel(Context context, int color, Bitmap bitmap) {
        super(context);
        this.color = color;
        setFocusable(true);
        setFocusableInTouchMode(true);

        this.setOnTouchListener(this);

        mBitmap = bitmap;
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(strockWidth);
        mPaint.setTextSize(30);

        mPath = new Path();
        //paths.add(new PathPoints(mPath, color,strockWidth, false));
        mCanvas = new Canvas();
    }

    public void colorChanged(int color) {
        this.color = color;
        mPaint.setColor(color);
    }

    public void changeWidthOfStrock(int strockWidth) {
        this.strockWidth = strockWidth;
        mPaint.setStrokeWidth(strockWidth);
    }

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        mHeight = View.MeasureSpec.getSize(heightMeasureSpec);

        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if(mBitmap != null) {
            float xscale = (float) w / (float) mBitmap.getWidth();
            float yscale = (float) h / (float) mBitmap.getHeight();
            if (xscale > yscale) // make sure both dimensions fit (use the
                xscale = yscale;

            int newx = mWidth;//= (int) ((int) w * xscale);
            int newy = mHeight;//= (int) ((int) h * xscale); // use the same scale for both dimensions
            System.out.println("Screen width-->"+newx);
            System.out.println("Screen height-->"+newy);
            System.out.println("mBitmap.getWidth()-->"+mBitmap.getWidth());
            System.out.println("mBitmap.getHeight()-->"+mBitmap.getHeight());

            if(mBitmap.getWidth() <= newx) {
                newx = mBitmap.getWidth();
            }

            if(mBitmap.getHeight() <= newy) {
                newy = mBitmap.getHeight(); 
            }

            mBitmap = Bitmap.createScaledBitmap(mBitmap, this.getWidth(),this.getHeight(), true);
            //mBitmap = getResizedBitmap(mBitmap, newx, newy);//Bitmap.createScaledBitmap(mBitmap, 453,311, true);
        } else {
            Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
            mBitmap = Bitmap.createBitmap(w, h, conf);
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        /*
         * Draw the image into center
         */
        //int cx = (mWidth - mBitmap.getWidth()) >> 1; // same as (...) / 2
        //int cy = (mHeight - mBitmap.getHeight()) >> 1;

        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        for (PathPoints p : paths) {
            mPaint.setColor(p.getColor());
            mPaint.setStrokeWidth(p.getStrockWidth());
            if (p.isTextToDraw()) {
                //canvas.drawText(p.textToDraw, p.x, p.y, mPaint);
            } else {
                canvas.drawPath(p.getPath(), mPaint);
            }
        }
        mPaint.setColor(SSL);
        mPaint.setStrokeWidth(strockWidth);
        canvas.drawPath(mPath, 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, SSL,strockWidth ,false));
        mPath = new Path();

    }

    private void drawText(int x, int y) {
        //Log.v(TAG, "Here");
        //Log.v(TAG, "X " + x + " Y " + y);
        this.x = x;
        this.y = y;
        paths.add(new PathPoints(color, textToDraw, true, x, y));
        // mCanvas.drawText(textToDraw, x, y, mPaint);
    }

    @Override
    public boolean onTouch(View arg0, MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (!isTextModeOn) {
                touch_start(x, y);
                invalidate();
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (!isTextModeOn) {
                touch_move(x, y);
                invalidate();
            }
            break;
        case MotionEvent.ACTION_UP:
            if (isTextModeOn) {
                drawText((int) x, (int) y);
                invalidate();
            } else {
                touch_up();
                invalidate();
            }
            break;
        }
        return true;
    }

    public void onClickUndo() {
        if (paths.size() > 0) {
            undonePaths.add(paths.remove(paths.size() - 1));
            invalidate();
        } else {

        }
        // toast the user
    }

    public void onClickRedo() {
        if (undonePaths.size() > 0) {
            paths.add(undonePaths.remove(undonePaths.size() - 1));
            invalidate();
        } else {

        }
        // toast the user
    }


    class PathPoints {
        private Path path;
        // private Paint mPaint;
        private int color;
        private int strockW;
        private String textToDraw;
        private boolean isTextToDraw;
        private int x, y;

        public PathPoints(Path path, int color,int strockWidth ,boolean isTextToDraw) {
            this.path = path;
            this.color = color;
            this.strockW = strockWidth;
            this.isTextToDraw = isTextToDraw;
        }

        public PathPoints(int color, String textToDraw, boolean isTextToDraw,int x, int y) {
            this.color = color;
            this.textToDraw = textToDraw;
            this.isTextToDraw = isTextToDraw;
            this.x = x;
            this.y = y;
        }

        public Path getPath() {
            return path;
        }

        public void setPath(Path path) {
            this.path = path;
        }

        /*
         * private Paint getPaint() { mPaint = new Paint();
         * mPaint.setAntiAlias(true); mPaint.setColor(color);
         * mPaint.setStyle(Paint.Style.STROKE);
         * mPaint.setStrokeJoin(Paint.Join.ROUND);
         * mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(6);
         * return mPaint; }
         */

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public int getStrockWidth() {
            return strockW;
        }

        public void setStrokWidth(int color) {
            this.strockW = color;
        }

        public String getTextToDraw() {
            return textToDraw;
        }

        public void setTextToDraw(String textToDraw) {
            this.textToDraw = textToDraw;
        }

        public boolean isTextToDraw() {
            return isTextToDraw;
        }

        public void setTextToDraw(boolean isTextToDraw) {
            this.isTextToDraw = isTextToDraw;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

    }


     private Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {

         int cx = (mWidth - mBitmap.getWidth()) >> 1; // same as (...) / 2
         int cy = (mHeight - mBitmap.getHeight()) >> 1;

         int width = bm.getWidth();
         int height = bm.getHeight();
         float scaleWidth = ((float) newWidth) / width;
         float scaleHeight = ((float) newHeight) / height;
         // CREATE A MATRIX FOR THE MANIPULATION
         Matrix matrix = new Matrix();
         // RESIZE THE BIT MAP
         matrix.postScale(scaleWidth, scaleHeight);

         // "RECREATE" THE NEW BITMAP
         //Bitmap resizedBitmap = Bitmap.createBitmap(bm, cx, cy, width, height, matrix, false);
         return Bitmap.createBitmap(bm, cx, cy, width, height, matrix, false);
     }


}
drawingPanel = new DrawingPanel(getApplicationContext(), Constant.ImageEdit.colors[0], Constant.PhotoBitmapCommon);
rl_imgEdit_image.addView(drawingPanel);

I do not understand How to add this class and where and How to add this in layout

how please tell me the way of how to use this in my layout also , I do not understand what is Constant.ImageEdit.colors[0], Constant.PhotoBitmapCommon); i have replace it with Color.Black , and replaced bitmap with Bitmap mBitmap = Bitmap.createBitmap(screenWidth,screenHeight, Bitmap.Config.ARGB_8888); in your drawingPanel = new DrawingPanel(getApplicationContext(), Constant.ImageEdit.colors[0], Constant.PhotoBitmapCommon);

its woring great Even I can place dot through it

android - How to keep last drawn path and not to get it removed when d...

android canvas touch gesture
Rectangle 27 12

public abstract class DialView extends View {

    private float centerX;
    private float centerY;
    private float minCircle;
    private float maxCircle;
    private float stepAngle;

    public DialView(Context context) {
        super(context);
        stepAngle = 1;
        setOnTouchListener(new OnTouchListener() {
            private float startAngle;
            private boolean isDragging;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    startAngle = touchAngle(touchX, touchY);
                    isDragging = isInDiscArea(touchX, touchY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (isDragging) {
                        float touchAngle = touchAngle(touchX, touchY);
                        float deltaAngle = (360 + touchAngle - startAngle + 180) % 360 - 180;
                        if (Math.abs(deltaAngle) > stepAngle) {
                            int offset = (int) deltaAngle / (int) stepAngle;
                            startAngle = touchAngle;
                            onRotate(offset);
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    isDragging = false;
                    break;
                }
                return true;
            }
        });
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        centerX = getMeasuredWidth() / 2f;
        centerY = getMeasuredHeight() / 2f;
        super.onLayout(changed, l, t, r, b);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        float radius = Math.min(getMeasuredWidth(), getMeasuredHeight()) / 2f;
        Paint paint = new Paint();
        paint.setDither(true);
        paint.setAntiAlias(true);
        paint.setStyle(Style.FILL);
        paint.setColor(0xFFFFFFFF);
        paint.setXfermode(null);
        LinearGradient linearGradient = new LinearGradient(
            radius, 0, radius, radius, 0xFFFFFFFF, 0xFFEAEAEA, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
        canvas.drawCircle(centerX, centerY, maxCircle * radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawCircle(centerX, centerY, minCircle * radius, paint);
        paint.setXfermode(null);
        paint.setShader(null);
        paint.setColor(0x15000000);
        for (int i = 0, n =  360 / (int) stepAngle; i < n; i++) {
            double rad = Math.toRadians((int) stepAngle * i);
            int startX = (int) (centerX + minCircle * radius * Math.cos(rad));
            int startY = (int) (centerY + minCircle * radius * Math.sin(rad));
            int stopX = (int) (centerX + maxCircle * radius * Math.cos(rad));
            int stopY = (int) (centerY + maxCircle * radius * Math.sin(rad));
            canvas.drawLine(startX, startY, stopX, stopY, paint);
        }
        super.onDraw(canvas);
    }

    /**
     * Define the step angle in degrees for which the
     * dial will call {@link #onRotate(int)} event
     * @param angle : angle between each position
     */
    public void setStepAngle(float angle) {
        stepAngle = Math.abs(angle % 360);
    }

    /**
     * Define the draggable disc area with relative circle radius
     * based on min(width, height) dimension (0 = center, 1 = border)
     * @param radius1 : internal or external circle radius
     * @param radius2 : internal or external circle radius
     */
    public void setDiscArea(float radius1, float radius2) {
        radius1 = Math.max(0, Math.min(1, radius1));
        radius2 = Math.max(0, Math.min(1, radius2));
        minCircle = Math.min(radius1, radius2);
        maxCircle = Math.max(radius1, radius2);
    }

    /**
     * Check if touch event is located in disc area
     * @param touchX : X position of the finger in this view
     * @param touchY : Y position of the finger in this view
     */
    private boolean isInDiscArea(float touchX, float touchY) {
        float dX2 = (float) Math.pow(centerX - touchX, 2);
        float dY2 = (float) Math.pow(centerY - touchY, 2);
        float distToCenter = (float) Math.sqrt(dX2 + dY2);
        float baseDist = Math.min(centerX, centerY);
        float minDistToCenter = minCircle * baseDist;
        float maxDistToCenter = maxCircle * baseDist;
        return distToCenter >= minDistToCenter && distToCenter <= maxDistToCenter;
    }

    /**
     * Compute a touch angle in degrees from center
     * North = 0, East = 90, West = -90, South = +/-180
     * @param touchX : X position of the finger in this view
     * @param touchY : Y position of the finger in this view
     * @return angle
     */
    private float touchAngle(float touchX, float touchY) {
        float dX = touchX - centerX;
        float dY = centerY - touchY;
        return (float) (270 - Math.toDegrees(Math.atan2(dY, dX))) % 360 - 180;
    }

    protected abstract void onRotate(int offset);

}
public class DialActivity extends Activity {

    @Override
    protected void onCreate(Bundle state) {
        setContentView(new RelativeLayout(this) {
            private int value = 0;
            private TextView textView;
            {
                addView(new DialView(getContext()) {
                    {
                        // a step every 20
                        setStepAngle(20f);
                        // area from 30% to 90%
                        setDiscArea(.30f, .90f);
                    }
                    @Override
                    protected void onRotate(int offset) {
                        textView.setText(String.valueOf(value += offset));
                    }
                }, new RelativeLayout.LayoutParams(0, 0) {
                    {
                        width = MATCH_PARENT;
                        height = MATCH_PARENT;
                        addRule(RelativeLayout.CENTER_IN_PARENT);
                    }
                });
                addView(textView = new TextView(getContext()) {
                    {
                        setText(Integer.toString(value));
                        setTextColor(Color.WHITE);
                        setTextSize(30);
                    }
                }, new RelativeLayout.LayoutParams(0, 0) {
                    {
                        width = WRAP_CONTENT;
                        height = WRAP_CONTENT;
                        addRule(RelativeLayout.CENTER_IN_PARENT);
                    }
                });
            }
        });
        super.onCreate(state);
    }

}

THank you for taking the time to write this, but unfortunatly I have already tried Maystro's answer and it worked. so he deserves the answer. too bad I can't split bounty as your answer works too. Cheers

android - How would I implement a swipe-based circular control like th...

android swipe
Rectangle 27 2

public class Main extends Activity implements OnColorChangedListener {
    // public static int selectedColor = Color.BLACK;
    public static ArrayList<Path> mMaindialog;
    // private ArrayList<Path> undonePaths;
    // public int selectedcolor;
    private static final String COLOR_PREFERENCE_KEY = "color";
    private FrameLayout relativelayout;
    static String sdpath, location;
    Boolean i;
    // Instance variables
    private Bitmap mBitmap = null;
    Bitmap bitmap;
    private Paint mPaint, mBitmapPaint, mPaint1;
    private MyView mView;
    ImageView idd;
    // private Path mPath;
    int slll = Color.BLACK;
    Bitmap map = ListView5.bMap;
    private Button ClearPaint, Colorpaint;
    Ghostdatabase gost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        idd = (ImageView) findViewById(R.id.imageView1);
        relativelayout = (FrameLayout) findViewById(R.id.frameLayout);

        DisplayMetrics metrics = getBaseContext().getResources()
                .getDisplayMetrics();
        int w = metrics.widthPixels;
        int h = metrics.heightPixels;

        System.out.println(" width " + w);
        System.out.println(" height " + h);

        mView = new MyView(this, w, h);
        mView.setDrawingCacheEnabled(true);

        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(4);

        ClearPaint = (Button) findViewById(R.id.ne);
        ClearPaint.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // mBitmap.eraseColor(Color.TRANSPARENT);
                // mPath.reset();
                // mView.invalidate();

                mView.onClickUndo();

            }
        });
        Button save22 = (Button) findViewById(R.id.save);
        save22.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                File cacheDir;
                Toast.makeText(Main.this, "Photo", 500).show();
                Bitmap icon;
                relativelayout.setDrawingCacheEnabled(true);

                icon = Bitmap.createBitmap(relativelayout.getDrawingCache());
                Bitmap bitmap = icon;
                relativelayout.setDrawingCacheEnabled(false);
                // File mFile1 = Environment.getExternalStorageDirectory();
                Date d = new Date();
                String fileName = d.getTime() + "mg1.jpg";

                File storagePath = (Environment.getExternalStorageDirectory());
                File dest = new File(storagePath + "/CityAppImages");

                if (!dest.exists()) {
                    dest.mkdirs();

                }

                File mFile2 = new File(dest, fileName);
                sdpath = mFile2.getAbsolutePath();

                Log.d("qqqqqqqqqqqqqqqqqqqqqqq", "zzzzzzzz" + sdpath);
                try {
                    FileOutputStream outStream;

                    outStream = new FileOutputStream(mFile2);

                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

                    outStream.flush();

                    outStream.close();
                    Toast.makeText(Main.this, "Photo Saved Sucessfully", 500)
                            .show();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {

                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(Main.this, "Photo Not Saved Sucessfully",
                            500).show();
                }

                gost = new Ghostdatabase(Main.this);
                gost.open();

                gost.insertTitle(sdpath);
            }
        });

        Button view = (Button) findViewById(R.id.listtt);
        view.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent ii = new Intent(Main.this, ListView5.class);
                startActivity(ii);

            }
        });

        Button Colorpaint = (Button) findViewById(R.id.Color);
        Colorpaint.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                int color = PreferenceManager.getDefaultSharedPreferences(
                        Main.this).getInt(COLOR_PREFERENCE_KEY, Color.WHITE);
                // int _color = R.color.red;
                new ColorPickerDialog(v.getContext(),
                        new OnColorChangedListener() {

                            public void colorChanged(int color) {
                                mPaint.setColor(color);

                                slll = color;

                                Log.i("TAG", "mpaint one" + mPaint);
                            }
                        }, mPaint.getColor()).show();
                Log.i("TAG", "mpaint two" + mPaint);
            }
        });
        relativelayout.addView(mView);
    }

    // //////////******************* Pinting view
    // *******************///////////////////

    public class MyView extends View implements OnTouchListener {
        private Map<Path, Integer> colorsMap = new HashMap<Path, Integer>();
        private ArrayList<Path> mMaindialog = new ArrayList<Path>();
        private ArrayList<Path> undonePaths = new ArrayList<Path>();
        int colorPicked = slll;
        // Paint mPaint1;

        private Canvas mCanvas;
        private Path mPath;

        public MyView(Context c, int w, int h) {
            super(c);
            if (GlobalVariable.impath == 1) {
                Log.d("", "111111" + GlobalVariable.impath);
                System.out.println(GlobalVariable.impath);
                Intent ii = getIntent();
                location = ii.getStringExtra("IMAGE");
                // bitmap.recycle();
                Log.d("", "location" + location);
                bitmap = BitmapFactory.decodeFile(location);
                mBitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                Log.d("hhhhhhhhhhhhhhhssssssss", "mBitmap" + mBitmap);
                // mBitmap = Bitmap.createBitmap(100, 100,
                // Bitmap.Config.ARGB_8888);
                // idd.setImageBitmap(mBitmap);
                Log.d("hhhhhhhhhhhhhhhssssssss", "GlobalVariable.impath"
                        + GlobalVariable.impath);
            } else if (GlobalVariable.impath == 2) {
                // bitmap.recycle();
                Log.d("", "22222222222222222222222" + GlobalVariable.impath);
                bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.base);
                mBitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
                // mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                Log.d("hhhhhhhhhhhhhhhssssssss1111111", "mBitmap" + mBitmap);
            }

            //
            mCanvas = new Canvas(mBitmap);
            mPath = new Path();

        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);

        }

        @Override
        protected void onDraw(Canvas canvas) {

            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

            for (Path p : mMaindialog) {
                mPaint.setColor(colorsMap.get(p));
                canvas.drawPath(p, mPaint);
            }
            mPaint.setColor(slll);
            canvas.drawPath(mPath, mPaint);
        }

        // //////************touching evants for painting**************///////
        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;
            undonePaths.clear();
        }

        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();
            mPath.reset();
            mMaindialog.add(mPath);
        }

        @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();
                undonePaths.clear();
                mPath.reset();
                mPath.moveTo(x, y);
                mX = x;
                mY = y;
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                // touch_move(x, y);
                // invalidate();
                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;
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                // touch_up();
                // invalidate();
                mPath.lineTo(mX, mY);
                mMaindialog.add(mPath);
                colorsMap.put(mPath, slll);
                mPath = new Path();
                mPath.reset();
                invalidate();
                break;
            }
            return true;
        } // end of touch events for image

        private Paint createPen(int colorPicked) {
            // TODO Auto-generated method stub
            mPaint1 = new Paint();
            mPaint1.setColor(colorPicked);
            mPaint1.setAntiAlias(true);
            mPaint1.setDither(true);
            mPaint1.setStyle(Paint.Style.STROKE);
            mPaint1.setStrokeJoin(Paint.Join.ROUND);
            mPaint1.setStrokeCap(Paint.Cap.ROUND);
            // mPaint1.setStrokeWidth(3);
            return mPaint1;
        }

        public void onClickRedo() {
            if (undonePaths.size() > 0) {
                mMaindialog.add(undonePaths.remove(undonePaths.size() - 1));
                mView.invalidate();

            } else {

            }
            // toast the user
        }

        public void onClickUndo() {
            if (mMaindialog.size() > 0) {
                undonePaths.add(mView.mMaindialog.remove(mView.mMaindialog
                        .size() - 1));
                mView.invalidate();
            }

            else {

            }
        }

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            // TODO Auto-generated method stub
            return false;
        }
    }// end MyView

    @Override
    public void colorChanged(int color) {
        // TODO Auto-generated method stub
        PreferenceManager.getDefaultSharedPreferences(this).edit()
                .putInt(COLOR_PREFERENCE_KEY, color).commit();
        slll = color;
    }

}

java - Undo and redo in Canvas for Android - Stack Overflow

java android android-canvas undo redo
Rectangle 27 8

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.

Hence, you cannot find out when somebody taps on a Button in your info window. You are welcome to respond to clicks anywhere on the info window, though.

Thanks your quick respond.So if button can't put in window.is this possible to identify event when user click info-window it self not the button.

@Sajith4U: Yes. I included a link in my last sentence to the documentation that explains how to use setOnInfoWindowClickListener() for this. Here is a sample project demonstrating its use: github.com/commonsguy/cw-omnibus/tree/master/MapsV2/Popups

Android custom InfoWindow Google Map v2 onclick button? - Stack Overfl...

android google-maps onclick customization infowindow
Rectangle 27 8

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.

Hence, you cannot find out when somebody taps on a Button in your info window. You are welcome to respond to clicks anywhere on the info window, though.

Thanks your quick respond.So if button can't put in window.is this possible to identify event when user click info-window it self not the button.

@Sajith4U: Yes. I included a link in my last sentence to the documentation that explains how to use setOnInfoWindowClickListener() for this. Here is a sample project demonstrating its use: github.com/commonsguy/cw-omnibus/tree/master/MapsV2/Popups

Android custom InfoWindow Google Map v2 onclick button? - Stack Overfl...

android google-maps onclick customization infowindow
Rectangle 27 1

remove overflow property from all canvas parents,probably we dont need this property on touch devices:

$("canvas").parents("*").css("overflow", "visible");

javascript - Android Native Browser duplicating HTML5 canvas (fine in ...

javascript android html5-canvas
Rectangle 27 1

remove overflow property from all canvas parents,probably we dont need this property on touch devices:

$("canvas").parents("*").css("overflow", "visible");

javascript - Android Native Browser duplicating HTML5 canvas (fine in ...

javascript android html5-canvas
Rectangle 27 5

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (e.g., after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.

Perhaps you should try to call showInfoWindow() somewhere again in your code.

Thanks, i totally missed this small note. But the problem is still here. I guess than I should create Views to show in InfoWindow not in getContentInfo() method but somewhere else ,and create another listener to notify me than image is downloaded and set into view. Looks quite annoying

quite annoying indeed... but seems plausible, please post it if you manage to make it work! I'm working on something similar and this could be helpful

progress bar - Android Google maps APIv2 InfoWindow and Markers - Stac...

android progress-bar android-imageview google-maps-android-api-2
Rectangle 27 4

If you don't want to touch maplabel.js, you can add this function to change the z-index of the parent of the labels (although if you have other canvas elements, you may need to alter the function):

//change the z-index of the canvas elements parents to move them above polygon layer
google.maps.event.addListenerOnce(map, 'idle', function(){
//var canvasElements = document.getElementsByTagName('canvas');//plain js to get the elements
var canvasElements = jQuery('canvas'); //jquery for easy cross-browser support
    for(var i=0; i<canvasElements.length; i++){
        canvasElements[i].parentNode.style.zIndex = 9999;
    }

});

I can't get this to work. The parentNode style index change is showing correctly in the inspector but the labels remain hidden.

javascript - Placing a MapLabel on top of a Polygon in Google Maps V3 ...

javascript google-maps polygon
Rectangle 27 4

If you don't want to touch maplabel.js, you can add this function to change the z-index of the parent of the labels (although if you have other canvas elements, you may need to alter the function):

//change the z-index of the canvas elements parents to move them above polygon layer
google.maps.event.addListenerOnce(map, 'idle', function(){
//var canvasElements = document.getElementsByTagName('canvas');//plain js to get the elements
var canvasElements = jQuery('canvas'); //jquery for easy cross-browser support
    for(var i=0; i<canvasElements.length; i++){
        canvasElements[i].parentNode.style.zIndex = 9999;
    }

});

I can't get this to work. The parentNode style index change is showing correctly in the inspector but the labels remain hidden.

javascript - Placing a MapLabel on top of a Polygon in Google Maps V3 ...

javascript google-maps polygon
Rectangle 27 1

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.

However you can use GoogleMap.OnInfoWindowClickListener to listen to click events on an info window.

android - Androdi google map onMarkerClick (Button) not work - Stack O...

android google-maps listener
Rectangle 27 4

It would seem that you will have to calculate whether or not the user is touching within the circular view. This will have to be achieved by overriding the touch event of the custom ImageView class that I assume you have already written.

Originally I had thought that drawing a circular area would have been enough, but that is not the case.

public class CustomImageView implements ImageView
{
    private Point centerPoint;
    private float radius;

    @Override
    protected void onDraw(Canvas canvasF) 
    {
        Drawable drawable = getDrawable();
        if(centerPoint == null)
        {
            centerPoint = new Point (getWidth() / 2, getHeight() / 2);
            /* 
             * if radius extends to edges, but if circular code 
             * exists already then we should already know what the 
             * radius is at this point I would assume.
             */
            radius = getWidth() / 2;
        }

        /*
         * remaining draw code for manipulating a circle.
         */
    }

    private boolean isInsideCircle(Point touchedPoint)
    {
         int distance = (int) Math.round(Math.pow(touchedPoint.x - centerPoint.x, 2) + Math.pow(touchedPoint.y - centerPoint.y, 2));

         if(distance < Math.pow(radius, 2))
         {
             return true;
         }
         else
         {
             return false;
         }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        Point touchedPoint = new Point(Math.round(event.getX()),   Math.round(event.getY()));

        if(isInsideCircle(touchedPoint))
        {
            return super.onTouchEvent(event);
        }

        return true;
    }
}

I might now end up adding this to my ImageView class to expand upon it and provide touch events only within the image when I need them as well.

If the image goes all the way to the edges then the radius is a little easier to determine. Otherwise, there will need to be a little extra done to figure out what the radius of the actual area is.

Thanks for your help, +1 for that

Create ImageView that is round, so click will work on round area only ...

android android-layout android-view
Rectangle 27 1

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.

Then, you don't able to handle the spinner click but only if infowindow is clicked.

So what can be done if on some location I want a spinner on top of it to display various items based on that location, and it has to be displayed on the Map.

Unfortunately you can't interact with your spinner if you insert it into your infowindow.

Adding Spinner in info window of marker in google Maps in Android - St...

android google-maps spinner infowindow
Rectangle 27 1

Here is a pretty good example for canvas and drawing

Tnx for your answer I saw it before In above link use this in upTouch: mPath.LineTo(mx,my); But i cant use this because i draw a line not path

i attach it in the first post, its the second time i ask in this site, i want to insert my totally code in post but site eror

I'm sorry, but it's still not enough I will need at least all the places when you use these sX, eX etc. variables... or I can search an other tutorial for you :/

I think your problem is that you always rewrite the variables where you store the touch start and touch and, you should put them in a list like in the example above.

android - End Canvas with touch up - Stack Overflow

android canvas graphic
Rectangle 27 4

Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.

For me the best method and the simplest one consists in applying a mask on the view, like that:

@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
    super.onSizeChanged(width, height, oldWidth, oldHeight);

    float cornerRadius = <whatever_you_want>;
    this.path = new Path();
    this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    if (this.path != null) {
        canvas.clipPath(this.path);
    }
    super.dispatchDraw(canvas);
}

This should be the most correct answer.

@MaksimKniazev Make a subclass of the layout you want (for instance: FrameLayout), then paste these two methods into this subclass and replace '<whatever_you_want>' with your desired corner radius value (from resources for example). That's it. Is it enough clear for you or do you need an example?

How to make a view in android with rounded corners - Stack Overflow

android android-layout android-view android-shape