I need to draw a circle as per my finger move so i have write this code
package com.sport;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class sport extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchView(this));
}
class TouchView extends View {
Bitmap bgr;
Bitmap overlayDefault;
Bitmap overlay;
Paint pTouch;
int X;
int Y;
Canvas c2;
public TouchView(Context context) {
super(context);
bgr = BitmapFactory.decodeResource(getResources(), R.drawable.new1);
overlayDefault = BitmapFactory.decodeResource(getResources(),
R.drawable.original);
overlay = BitmapFactory.decodeResource(getResources(),
R.drawable.new1).copy(Config.ARGB_8888, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.DEV_KERN_TEXT_FLAG);
pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
pTouch.setColor(Color.TRANSPARENT);
// pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int ht = displaymetrics.heightPixels;
int wt = displaymetrics.widthPixels;
X = wt / 2;
Y = 0;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
X = (int) ev.getX();
Y = (int) ev.getY();
//invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
X = (int) ev.getX();
Y = (int) ev.getY();
/* Toast.makeText(getBaseContext(),"x is::"+ X,
Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(),"Y is::"+ Y,
Toast.LENGTH_LONG).show();*/
//c2.drawCircle(X, Y, 70, pTouch);
/*System.out.println("x is"+X);
System.out.println("Y is"+Y);*/
invalidate();
break;
}
case MotionEvent.ACTION_UP:
X = (int) ev.getX();
Y = (int) ev.getY();
/*
* Toast.makeText(getBaseContext(),"x is::"+ X,
* Toast.LENGTH_LONG).show();
* Toast.makeText(getBaseContext(),"Y is::"+ Y,
* Toast.LENGTH_LONG).show();
*/
//invalidate();
break;
case MotionEvent.ACTION_POINTER_ID_MASK :
/*X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();*/
break;
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int ht = displaymetrics.heightPixels;
int wt = displaymetrics.widthPixels;
int heightbitmap = bgr.getHeight();
int widthbitmap = bgr.getWidth();
int minus = wt - widthbitmap;
// draw background
canvas.drawBitmap(bgr, minus / 2, 0, null);
// copy the default overlay into temporary overlay and punch a hole
// in it
c2.drawBitmap(overlayDefault, 360, 0, null); // exclude this line to
// show all as you
Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.diff_6); // draw
//c2.drawBitmap(_scratch, 10, 10, pTouch);
if(X >= 470 & X <= 522)
{
if(Y >= 255 & Y<= 330)
{
//c2.drawRect(X, Y, 5, 5, pTouch);
double outer_radius = 0.5 * Math.sqrt((_scratch.getWidth()) * (_scratch.getWidth())+ (_scratch.getHeight()) * (_scratch.getHeight()));
float f = (float) outer_radius;
c2.drawCircle(X, Y, f, pTouch);
}
}
// draw the overlay over the background
canvas.drawBitmap(overlay, minus/2, 0, null);
}
}
}
Problem::
when i touch on screen circle are stay at right side of my finger Like this.
but i need it center of my finger please help on this
The problem is because you create 'overlay' with respect to the x and y cordinates from the touch event and later copying this onto the background with an offset (minus/2). Assuming your background image is smaller than the screen resolution the circle will always shift right and hence will look the circle is at the right of your finger.
If you use a background image which has same resolution as the screen dimensions , you will get properly drawn circle, with its centre at the point of touch.
Related
I have a custom view in my project. In the view class I draw a line using onDraw method. The height of the line can be changed by swiping up and down.How can I set a max and min value for the height of that line?
This is my code
package com.example.richyrony.draw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
/**
* Created by Richy & Rony on 26-01-2018.
*/
public class Line extends View {
PointF topLeft = new PointF(100, 100);
PointF topRight = new PointF(290, 100);
PointF bottomLeft = new PointF(100, 290);
PointF bottomRight = new PointF(290, 290);
private final int NONE = -1, TOUCH_TOP_LEFT = 0, TOUCH_TOP_RIGHT = 1, TOUCH_BOT_LEFT = 2, TOUCH_BOT_RIGHT = 3;
int currentTouch = NONE;
Float lineTwoStartx = 250f;
Float lineTwoStart = 50f;
Float lineTwoEndx = 250f;
Float lineTwoEnd = 200f;
Float lineOneStartx = 50f;
Float lineOneStart = 50f;
;
Float lineOneEndx = 50f;
Float lineOneEnd = 200f;
RectF touchArea = new RectF(0, 0, 350, 350);
Paint paint;
public Line(Context context) {
super(context);
paint = new Paint();
paint.setStrokeWidth(4);
paint.setColor(Color.parseColor("#000000"));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(lineOneStartx, lineOneStart, lineOneEndx, lineOneEnd, paint);
canvas.drawLine(lineTwoStartx, lineTwoStart, lineTwoEndx, lineTwoEnd, paint);
canvas.drawLine(lineOneEndx, lineOneEnd, lineTwoEndx, lineTwoEnd, paint);
canvas.drawLine(lineOneStartx, lineOneStart, lineTwoStartx, lineTwoStart, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
//The user just put their finger down.
//We check to see which corner the user is touching
//And set our global, currentTouch, to the appropriate constant.
case MotionEvent.ACTION_DOWN:
if (touchArea.contains(event.getX(), event.getY())) {
currentTouch = TOUCH_TOP_LEFT;
Toast.makeText(getContext(), "tf" + currentTouch, Toast.LENGTH_SHORT).show();
} else {
return false; //Return false if user touches none of the corners
}
return true; //Return true if the user touches one of the corners
//Now we know which corner the user is touching.
//When the user moves their finger, we update the point to the user position and invalidate.
case MotionEvent.ACTION_MOVE:
switch (currentTouch) {
case TOUCH_TOP_LEFT:
lineOneEnd = event.getY();
invalidate();
return true;
}
//We returned true for all of the above cases, because we used the event
return false; //If currentTouch is none of the above cases, return false
//Here the user lifts up their finger.
//We update the points one last time, and set currentTouch to NONE.
case MotionEvent.ACTION_UP:
switch (currentTouch) {
case TOUCH_TOP_LEFT:
lineOneEnd = event.getY();
currentTouch = NONE;
invalidate();
return true;
}
return false;
}
return false;
}
}
And also if anyone has any idea on how to measure angles between two lines it would be helpful
I am trying to get this paddle_user to move vertically on when the screen is touched. But the paddle isn't moving. I've double checked the onTouch Code but i'm still no closer to finding out what I am doing wrong.
package com.nblsoft.pong;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
public class PongLogic extends View implements View.OnTouchListener {
//set screen constrains in dip
Configuration configuration = this.getResources().getConfiguration();
int dpHeight = configuration.screenHeightDp; //The current height of the available screen space, in dp units, corresponding to screen height resource qualifier.
int dpWidth = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
//int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.
//DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
//float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
//float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
private int dptopixel(int DESIRED_DP_VALUE){
final float scale = getResources().getDisplayMetrics().density;
return (int)((DESIRED_DP_VALUE) * scale + 0.5f);
}
private int pixeltodp(int DESIRED_PIXEL_VALUE){
final float scale = getResources().getDisplayMetrics().density;
return (int) ((DESIRED_PIXEL_VALUE) - 0.5f / scale);
}
//set paddle size, speed, position vector
int paddle_pos_x = 4 * (dptopixel(dpWidth)/100); //3 for 320x480, 10 for 1080x1920 etc.
int paddle_width = (dptopixel(dpWidth)/10); //
int paddle_pos_y = (dptopixel(dpHeight)/10); //48 for 320x480, 190 for 1080x1920 etc.
int paddle_height = (dptopixel(dpHeight)/100) + 3; //the paddle is 100% of the total height of phone.
int user_paddle_pos_x = 4 * (dptopixel(dpWidth)/100) ;
int user_paddle_pos_y = dptopixel(dpHeight) - ((dptopixel(dpHeight)/10) + (dptopixel(dpHeight)/100) + 3) ;
//User Paddle
public Rect paddle_user = new Rect(user_paddle_pos_x,
user_paddle_pos_y,
user_paddle_pos_x + paddle_width,
user_paddle_pos_y + paddle_height);
//AI paddle
Rect paddle_AI = new Rect(paddle_pos_x,
paddle_pos_y,
paddle_pos_x + paddle_width,
paddle_pos_y + paddle_height);
//set ball position vector, Velocity vector, acceleration
//Override onDraw method
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint mytext = new Paint();
mytext.setColor(Color.WHITE);
// Draw Middle point
canvas.drawRect(0, ((dptopixel(dpHeight)) / 2), (dptopixel(dpWidth)), (((dptopixel(dpHeight)) / 2) + 2), mytext);
canvas.drawRect(paddle_user,mytext);
canvas.drawRect(paddle_AI, mytext);
//Practise Methods
//canvas.drawText(Integer.toString(dptopixel(dpHeight)),300,300,mytext);
//canvas.drawText(Integer.toString(dptopixel(dpWidth)), 400, 400, mytext);
//canvas.drawText(Integer.toString(dpHeight),500,500,mytext);
//canvas.drawText(Integer.toString(dpWidth),600,600,mytext);
//canvas.drawText("Fuck", 700, 700, mytext);
//canvas.drawRect(0,0,dptopixel(dpWidth),dptopixel(dpHeight),mytext);
}
//Override Touch method
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
paddle_user.offsetTo(10,0);
}
return true; //Event Handled
}
public PongLogic(Context context) {
super(context);
setBackgroundColor(Color.BLACK); //to set background
this.setFocusableInTouchMode(true); //to enable touch mode
this.setOnTouchListener(this);
}
}
You have to implement the OnTouchListener interface and do this.setOnTouchListener(this).
Edit:
public class CustomClass extends View implements View.OnTouchListener{}
then in your constructor you add this.setOnTouchListener(this);
Edit2:
Ok so I forgot to tell you but when you does some modification for exemple with you rect you have to call the draw method and to do that properly you call invalidate. So in your ontouch method add invalidate().
here is the code that I did if you wan to check (I just cut your code to have a easier exemple):
public class PongLogic extends View implements View.OnTouchListener {
//set ball position vector, Velocity vector, acceleration
Rect paddle_user = new Rect(0, 100, 100, 200);
public PongLogic(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnTouchListener(this);
setBackgroundColor(Color.BLACK); //to set background
this.setFocusableInTouchMode(true);
}
//Override onDraw method
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint mytext = new Paint();
mytext.setColor(Color.WHITE);
mytext.setStyle(Paint.Style.STROKE);
mytext.setStrokeWidth(2);
canvas.drawRect(paddle_user, mytext);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
paddle_user.offsetTo(0,0);
invalidate();
return false;
}
}
So what you missed was basically the invalidate() method. So what you did in the begging was not wrong with the first OnTouch method but better to do with the interface if you make a custom view.
I have two images, one above one and i want to make the upper image transparent when user erase it and covered image should be shown...hear is my code
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class StartActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchView(this));
}
class TouchView extends View{
Bitmap bgr;
Bitmap overlayDefault;
Bitmap overlay;
Paint pTouch;
int X = -100;
int Y = -100;
Canvas c2;
public TouchView(Context context) {
super(context);
bgr = BitmapFactory.decodeResource(getResources(),R.drawable.bgr);
overlayDefault = BitmapFactory.decodeResource(getResources(),R.drawable.over);
overlay = BitmapFactory.decodeResource(getResources(),R.drawable.over).copy(Config.ARGB_8888, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
pTouch.setColor(Color.TRANSPARENT);
pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_UP: {
break;
}
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//draw background
canvas.drawBitmap(bgr, 0, 0, null);
//copy the default overlay into temporary overlay and punch a hole in it
c2.drawBitmap(overlayDefault, 0, 0, null); //exclude this line to show all as you draw
c2.drawCircle(X, Y, 80, pTouch);
//draw the overlay over the background
canvas.drawBitmap(overlay, 0, 0, null);
}
}
}
But I am getting error at line:
pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
The error is:
"SRC_OUT cannot be resolved or is not a field".
Close, you need to ensure your Mode is from the correct package. What you should use is:
android.graphics.PorterDuff.Mode
Changing the problem line to:
pTouch.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
I am developing mind mapping tool for android. Till now the objects are drawn on screen ontouch event. I want to create one main object and draw this type of lines from that object. The example is,
http://www.biggerplate.com/mapImages/xl/e666ca33-abf7-4cc7-acc9-4aea9487feef.png
Please Help.
This is the class to draw a node touch events
package com.example.mindmapping;
import java.util.LinkedList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
public class CreateBitmap extends Activity {
Bitmap bitmap;
SurfaceHolder holder;
//LinkedList<newNode> nodes;
LinkedList<Node> nodes;
float x, y;
Node node;
Boolean collision;
SurfaceView surfaceView;
Context baseCtx;
//DrawMindMap dm;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
baseCtx = this.getBaseContext();
setContentView(R.layout.drawmindmap);
nodes = new LinkedList<Node>();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rectangle_small);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
holder = surfaceView.getHolder();
surfaceView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("TOUCH", "On touch start, total nodes: " + String.valueOf(nodes.size()));
x = event.getX();
Log.d("XPOS", "touch x" + String.valueOf(x));
y = event.getY();
Log.d("YPOS", "touch y" + String.valueOf(y));
Canvas c = holder.lockCanvas();
//c.drawColor(Color.BLACK);
Node n = new Node(bitmap, c, x, y);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
collision = false;
//nodes.add(n);
if (!nodes.isEmpty()){
for (Node no : nodes) {
collision = no.isHere(x, y);
if (collision){
break;
}
}
}
if(!collision){
nodes.add(n);
}
c.drawColor(Color.BLACK);
if (!nodes.isEmpty()){
for (Node no : nodes) {
no.Draw();
c.drawLine(x, y, event.getX(), event.getY(), paint);
Log.d("Node POS","Node X,Y: " + String.valueOf(no.xPosition) + " " + String.valueOf(no.yPosition));
}
}
holder.unlockCanvasAndPost(c);
break;
}
return true;
}
});
}
In the class given below is used to handle and draw node
package com.example.mindmapping;
import android.graphics.Bitmap;
import android.graphics.Canvas;
public class Node {
public Bitmap img;
public Canvas c;
public float xPosition, yPosition, topLeft;
int width, height,gResId;
boolean isItOk;
public Node(Bitmap b,Canvas canv, float xP, float yP) {
img = b;
c = canv;
width = b.getWidth();
height = b.getHeight();
xPosition = xP - (width/2);
yPosition = yP - (height/2);
}
public void SetPos( float xP, float yP) {
xPosition = xP - (width/2);
yPosition = yP - (height/2);
}
public boolean isHere(float x, float y){
x = (float) (x + width * 0.5);
y = (float) (y + height * 0.5);
if((x > xPosition - width * 0.5) && (x < xPosition + width * 0.5) && (y > yPosition - height * 0.5) && (y < yPosition + height * 0.5) ){
return true;
}
return false;
}
//#SuppressWarnings("static-access")
public void Draw() {
c.drawBitmap(img, xPosition, yPosition, null);
}
}
I am using an ImageView to create a canvas and draw elements with finger touch on it. But the problem is that, firstly the canvas only covers a little portion of the screen to draw or write something and secondly it produces lines or curves far away where I touch. I have one textview and the imageview in linear layout. Please check my code and help me for the same.
DrawTestActivity.java:
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Path path;
Paint paint;
float downx = 0, downy = 0, upx = 0, upy = 0;
float startX = 0;
float startY = 0;
float endX = 0;
float endY = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.imageView1);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
startX=event.getX();
startY=event.getY();
break;
case MotionEvent.ACTION_MOVE:
endX = event.getX();
endY = event.getY();
canvas.drawLine(startX,startY,endX,endY, paint);
imageView.invalidate();
startX=endX;
startY=endY;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}