coordinates inside a canvas on android - java

I'm development an app for drawing lines between two points. For example:
I have a map like this (Please imagine The X are dots):
X X X X X X X X X X
Each one have been created with this sentence:
canvas.drawCircle(50, 100, 15, paint);
canvas.drawCircle(148, 100, 15, paint);
canvas.drawCircle(246, 100, 15, paint);
canvas.drawCircle(344,100,15,paint);
canvas.drawCircle(442,100,15,paint);
canvas.drawCircle(540,100,15,paint);
canvas.drawCircle(638,100,15,paint);
canvas.drawCircle(736,100,15,paint);
canvas.drawCircle(834,100,15,paint);
canvas.drawCircle(932,100,15,paint);
And I use a listener for catch the position of user interaction
case MotionEvent.ACTION_UP:
downx = event.getX();
downy = event.getY();
The problem is when I make clic between the points (932,100) and (832,100) the X position return 771 and it is not a value between 832 and 932.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int PMaxX=0;
int PMaxY =0;
final ArrayList<ArrayList<Integer>> Matriz = new ArrayList<ArrayList<Integer>>();
if (android.os.Build.VERSION.SDK_INT >= 13) {
display.getSize(size);
PMaxX = size.x;
PMaxY = size.y;
} else if (android.os.Build.VERSION.SDK_INT < 13) {
// Log.d("State", "Prueba menor 13");
PMaxX = display.getWidth();
PMaxY = display.getHeight();
}
Bitmap bitmap = Bitmap.createBitmap(PMaxX, PMaxY, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.rgb(0, 0, 0));
paint.setStrokeWidth(10);
canvas.drawCircle(50, 100, 15, paint);
canvas.drawCircle(148, 100, 15, paint);
canvas.drawCircle(246, 100, 15, paint);
canvas.drawCircle(344,100,15,paint);
canvas.drawCircle(442,100,15,paint);
canvas.drawCircle(540,100,15,paint);
canvas.drawCircle(638,100,15,paint);
canvas.drawCircle(736,100,15,paint);
canvas.drawCircle(834,100,15,paint);
canvas.drawCircle(932,100,15,paint);
canvas.drawCircle(1065,100,15,paint);
drawingImageView.setImageBitmap(bitmap);
drawingImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
downx = event.getX();
downy = event.getY();
Log.d("State","Show X" + Float.toString(downx));
Log.d("State","Show Y" + Float.toString(downy));
break;
default:
break;
}
return true;
}
});
}

Related

can't draw shapes on canvas

I have created a custom view so that i can draw shapes on clicks and preform some action
and i have created a method called fillOnTouch(); which is supposed to take a paint and canvas as parameters then draw colored circles on the canvas when i call this method from TouchEvent it doesn't draw on the canvas so I tried to create a path called coloredCircles and have added shapes to it on Touchevent then draw this path on onDraw method but the result is the same the shapes aren't drawen in the canvas as it's supposed to be
onTouchEvent
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
coloredCircles.addCircle(x, y, 20, Path.Direction.CW);
checkStrokeInRightPath(x, y);
FillLetters.fillCircleOnTouch(x, y, fillCircles, dataLists, mCanvas);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
checkStrokeInRightPath(x, y);
FillLetters.fillCircleOnTouch(x, y, fillCircles, dataLists, mCanvas);
coloredCircles.addCircle(x, y, 20, Path.Direction.CW);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
checkStrokeInRightPath(x, y);
FillLetters.fillCircleOnTouch(x, y, fillCircles, dataLists, mCanvas);
coloredCircles.addCircle(x, y, 20, Path.Direction.CW);
invalidate();
break;
}
return true;
}
fillOnTouch Method
public static void fillCircleOnTouch(float x, float y, Paint paint, List<List<Integer>> circleList, Canvas canvas) {
List<Integer> xPoints, yPoints, circleCount;
int r = DrawLetters.radius;
float xStart, xEnd, yStart, yEnd;
if (!circleList.isEmpty()) {
xPoints = circleList.get(0);
yPoints = circleList.get(1);
circleCount = circleList.get(2);
if (iterationCount < xPoints.size()) {
float nextCircleX = xPoints.get(iterationCount);
float nextCircleY = yPoints.get(iterationCount);
paint.setColor(blendColors("#FFFF00", "#0000FF", (circleCount.get(iterationCount)) * ((float) (1.0 / xPoints.size()))));
xStart = nextCircleX - r;
xEnd = nextCircleX + r;
yStart = nextCircleY - r;
yEnd = nextCircleY + r;
Range<Float> xRange = new Range<>(xStart, xEnd);
Range<Float> yRange = new Range<>(yStart, yEnd);
if (xRange.contains(x) && yRange.contains(y)) {
canvas.drawCircle(nextCircleX, nextCircleY, r, paint);
iterationCount++;
}
}
}
}
onDraw Method
#Override
protected void onDraw(Canvas canvas) {
// save the current state of the canvas before,
// to draw the background of the canvas
canvas.save();
// DEFAULT color of the canvas
int backgroundColor = Color.WHITE;
mCanvas.drawColor(backgroundColor);
// now, we iterate over the list of paths
// and draw each path on the canvas
for (Stroke fp : paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.width);
mCanvas.drawPath(fp.path, mPaint);
}
if (coloredCircles != null && !coloredCircles.isEmpty()) {
canvas.drawPath(coloredCircles, mPaint);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}

Bitmap from ImageView - always in corner of screen, not possible to move | Android Studio

this is my very first experience here on stackoverflow :). I hope i don't break any rule with my first question.
I want to get color from bitmap but i have a problem with converting Imageview to Bitmap. Wherever i put my ImageView on screen, it's moving to (0,0) screen position after converting it to Bitmap. The worst thing is that this is not visible on screen, but when i try to catch color from 'empty' position it gives me "color". Im attaching screens because im sure im not understandable now :D.
clicked on area where is invisible bitmap and catching color)
clicked on area where bitmap is located but it doesn't catch color
I really don't know what is wrong. sitting whole week on this case and i registered here to ask you...
It may be stupid thing because im newbie. Thanks for any help...
public class Game extends AppCompatActivity {
private boolean isTouch = false;
private ImageView imageOpponent;
private Bitmap bitmap1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
ImageView image = findViewById(R.id.imageView3);
ImageView imageAim = findViewById(R.id.imageAim);
ImageView imageMove = findViewById(R.id.imageView4);
ImageView imageShoot = findViewById(R.id.imageShoot);
ImageView imageBackground = findViewById(R.id.imageBackground);
//FrameLayout shootingFrame = findViewById(R.id.shootingFrame);
//Bitmap bitmap = imageBackground.getDrawingCache();
Bitmap bitmap = ((BitmapDrawable)imageBackground.getDrawable()).getBitmap();
imageOpponent = findViewById(R.id.imageOpponent);
imageOpponent.setDrawingCacheEnabled(true);
imageOpponent.buildDrawingCache(true);
TextView textX = findViewById(R.id.textView1);
TextView textY = findViewById(R.id.textView2);
//textX.setText(String.valueOf(xSize));
image.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
float xSize = image.getWidth();
float ySize = image.getHeight();
float xMaxShootingFrame = imageBackground.getWidth();
float yMaxShootingFrame = imageBackground.getHeight();
float xMoveSize = imageMove.getLayoutParams().width;
float yMoveSize = imageMove.getLayoutParams().height;
textY.setText(String.valueOf(xMaxShootingFrame));
float X = (float) event.getX() - (xMoveSize/2);
float Y = (float) event.getY() - (yMoveSize/2);
float xCalculated = 100 * event.getX() / xSize;
xCalculated = xCalculated/100;
float yCalculated = 100 * event.getY() / ySize;
yCalculated = yCalculated/100;
int eventaction = event.getAction();
//if ((X >= 0 && Y >= 0) || (X <= 100 && Y <= 100))
if ((X >= (0-(xMoveSize/2)) && X <= (xSize-(xMoveSize/2)) && (Y >= (0-(yMoveSize/2)) && Y <= (ySize-(yMoveSize/2))))) {
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
//Toast.makeText(Game.this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
imageMove.setX(X);
imageMove.setY(Y);
imageAim.setX(xMaxShootingFrame*xCalculated-xMoveSize/2);
imageAim.setY(yMaxShootingFrame*yCalculated-yMoveSize/2);
textX.setText(String.valueOf(xCalculated));
isTouch = true;
break;
case MotionEvent.ACTION_MOVE:
//Toast.makeText(Game.this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
imageMove.setX(X);
imageMove.setY(Y);
imageAim.setX(xMaxShootingFrame*xCalculated-xMoveSize/2);
imageAim.setY(yMaxShootingFrame*yCalculated-yMoveSize/2);
//textX.setText(String.valueOf(bitmap.getHeight()));
break;
case MotionEvent.ACTION_UP:
//Toast.makeText(Game.this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
imageMove.setX(X);
imageMove.setY(Y);
imageAim.setX(xMaxShootingFrame*xCalculated-xMoveSize/2);
imageAim.setY(yMaxShootingFrame*yCalculated-yMoveSize/2);
//textX.setText(String.valueOf(bitmap.getHeight()));
break;
}
}
float xxx = imageAim.getX();
float yyy = imageAim.getY();
return true;
}
});
imageShoot.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
bitmap1 = imageOpponent.getDrawingCache();
Bitmap bitmapBackground = ((BitmapDrawable)imageBackground.getDrawable()).getBitmap();
float xMoveSizex = imageAim.getLayoutParams().width;
float yMoveSizey = imageAim.getLayoutParams().height;
int x = (int)imageAim.getX() + ((int)xMoveSizex/2);
int y = (int)imageAim.getY() + ((int)yMoveSizey/2);
//Bitmap bitmap69 = Bitmap.createScaledBitmap(bitmap1, imageOpponent.getWidth(), imageOpponent.getHeight(), false);
textX.setText(String.valueOf(bitmap1.getHeight()));
textY.setText(String.valueOf(bitmap1.getWidth()));
if (x <= bitmap1.getWidth() && y <= bitmap1.getHeight()) {
int pixel = bitmap1.getPixel(x, y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
//if (redValue == 0 && blueValue == 0 && greenValue == 0){
//imageBackground.setBackgroundColor(Color.rgb(redValue,greenValue,blueValue));
if (bitmap1.getPixel(x, y) == Color.TRANSPARENT) {
textY.setText("Black " + x + " " + y);
} else {
textY.setText("Any Color");
}
}
return true;
}
});
}
}

Surfaceview with bitmap touchevent

I have a Surfaceview Class called ChickenView and I'm trying to make my bMapEgg have a touchevent. I tried using this bMapEgg.setOnTouchListener(this);
but it didn't work. Any ideas?
public void drawCourt() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
//Paint paint = new Paint();
canvas.drawColor(Color.BLACK);//the background
paint.setColor(Color.argb(255, 255, 255, 255));
paint.setTextSize(45);
canvas.drawText("Score:" + score + " Lives:" + lives + " fps:" + fps, 20, 40, paint);
Bitmap bMapEgg = BitmapFactory.decodeResource(getResources(), R.drawable.egg);
bMapEgg = scaleDown(bMapEgg,180,true);
Bitmap bMapBackground = BitmapFactory.decodeResource(getResources(), R.drawable.backgrounddd);
canvas.drawBitmap(bMapBackground, 0, 0, paint);
canvas.drawBitmap(bMapEgg, ballPosition.x, ballPosition.y, paint);
ourHolder.unlockCanvasAndPost(canvas);
}
}
First, you need to setup a touch listener for the whole SurfaceView. Next, to check whether the bitmap was touched you need to do something like this:
float x = touchEvent.getX();
float y = touchEvent.gety();
// Replace these with the correct values (bitmap x, y, width & height)
float x1 = bitmapPositionX;
float x2 = x1 + bitmapWidth;
float y1 = bitmapPositionY;
float y2 = y1 + bitmapHeight;
// Test to see if touch is inside the bitmap
if (x > x1 && x < x2 && y > y1 && y < y2) {
// Bitmap was touched
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN: (bitmap was just touched) break;
case TouchEvent.ACTION_DOWN: (user lifted finger from bitmap) break;
}
}

How to get all x and y coordinates of an imageview in Android?

I am implementing an app for getting the correct x and y location of the image-view and x and y coordinates of an image-view when I move the position of images on the screen. When I run the app and when I move my image-view it will get only 0 and 1. Is there a way for find out the x and y location?
Here is my Main-activity class:
public class MainActivity extends Activity{
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
int[] location = new int[4];
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView image = (ImageView) findViewById(R.id.ImageViewOne);
final Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
R.drawable.yellowrose);
image.setImageBitmap(icon);
image.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
final ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
System.out.println("mode = drag");
RectF r = new RectF();
matrix.mapRect(r);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
System.out.println("mode = none = " + mode);
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG)
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x,
event.getY() - start.y);
}
else if (mode == ZOOM)
{
float newDist = spacing(event);
if (newDist > 10f)
{
matrix.set(savedMatrix);
float scale = newDist / oldDist;
System.out.println("scale " + scale);
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f)
{
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
System.out.println("mode " + mode);
}
break;
}
// Perform the transformation
view.setImageMatrix(matrix);
return true;
}
});
}
private float spacing(MotionEvent event)
{
float x = event.getRawX() - event.getRawX();
System.out.println("spacing x" + x);
float y = event.getRawY() - event.getRawY();
System.out.println("spacing y" + y);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event)
{
float x = event.getRawX() + event.getRawX();
System.out.println("midpoint x" + x);
float y = event.getRawY() + event.getRawY();
System.out.println("midpoint y" + y);
point.set(x / 2, y / 2);
}
}
I am using View.getLocationOnScreen(int[]) to get X and Y of a view relative to its parent/screen:
int[] posXY = new int[2];
myView.getLocationOnScreen(posXY);
int x = posXY[0];
int y = posXY[1];

Cannot draw canvas with desired Bitmap after OnTouchEvent

I am making a tictactoe android application . After making on customview called TicTacToeGFX I tried to make an onTouchEvent which (after taking into account) the coordinates of the touch , it would fill the corresponding rectangle with the bitmap circle or cross. The Problem is that in the onTouchEvent I cannot redraw the canvas with the desired Bitmap. So my question is How to I re-draw a canvas after an onTouchEvent?
public class NewGame extends Activity {
TicTacToeGFX Game;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Game = new TicTacToeGFX(this);
setContentView(Game);
}
}
public class TicTacToeGFX extends View {
int x, y;
int rectanglescounter = 0;
public Rect[] rectangles = new Rect[9];
// BitMap
Bitmap cross = BitmapFactory.decodeResource(getResources(),
R.drawable.cross1);
Bitmap circle = BitmapFactory.decodeResource(getResources(),
R.drawable.circle1);
Bitmap empty = BitmapFactory.decodeResource(getResources(),
R.drawable.empty1);
Paint paint = new Paint();
Canvas canvas = new Canvas();
public TicTacToeGFX(Context context) {
super(context);
setFocusable(true);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// -------------------------------------------calculate
// screen------------------------------------------------------
x = (int) ((getWidth()) / 3);
y = (int) ((getHeight()) / 3);
// //------------------------------------------- calculate rectangle
// positions on
// screen------------------------------------------------------
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rectangles[rectanglescounter] = new Rect((x * j), (y * i),
((x * j) + x), ((y * i) + y));
if (rectanglescounter < 8)
rectanglescounter++;
else
break;
}
}
// ------------------------------------------- draw the canvas with
// empty Bitmap
// ------------------------------------------------------
int counter = 0;
canvas.drawRGB(0, 0, 0);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
canvas.drawBitmap(empty, null, rectangles[counter], null);
counter++;
}
}
// ------------------------------------------- draw
// LinesS------------------------------------------------------
paint.setColor(Color.WHITE);
canvas.drawLine(x, 0, x, 3 * y, paint);// 1h
canvas.drawLine(2 * x, 0, 2 * x, 3 * y, paint);// 2h
canvas.drawLine(0, y, 3 * x, y, paint);// 3h
canvas.drawLine(0, 2 * y, 3 * x, 2 * y, paint);// 4h
}
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
x = (int) event.getX();
y = (int) event.getY();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getContext(), "Hello", 1).show();
canvas.drawRGB(0, 0, 0);
invalidate();
break;
case MotionEvent.ACTION_MOVE: // touch drag with the ball
// move the balls the same as the finger
break;
}
return true;
}
}

Categories