I have created two different projects in android for rotating and Drag and drop. Those are working fine. But, I need to integrate those in a single project. Please help,
Thanks in advance.
Both MainActivity code displayed below:
//This is draganddrop MainActivity.java code
package com.example.draganddrop;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener
{
MySurfaceView MSV;
float x, y;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MSV = new MySurfaceView(this);
MSV.setOnTouchListener(this);
x = 0;
y = 0;
setContentView(MSV);
}
protected void onPause()
{
super.onPause();
MSV.pause();
}
protected void onResume()
{
super.onResume();
MSV.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
x = event.getX();
y = event.getY();
return true;
}
public class MySurfaceView extends SurfaceView implements Runnable
{
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MySurfaceView(Context context)
{
super(context);
ourHolder = getHolder();
}
public void pause()
{
isRunning = false;
while(true)
{
try
{
ourThread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume()
{
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run()
{
while(isRunning)
{
if(!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(12, 12, 150);
if(x != 0 && y != 0)
{
Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.colorball);
canvas.drawBitmap(test, x-(test.getWidth()/2), y-(test.getHeight()/2), null);
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
}
//This is rotate MainActivity.java code
package com.example.rotatetest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener {
private ImageView mCircle;
private double mCurrAngle = 0;
private double mPrevAngle = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircle = (ImageView) findViewById(R.id.imageView1);
mCircle.setOnTouchListener( this); // Your activity should implement OnTouchListener
}
#Override
public boolean onTouch(View v, MotionEvent event) {
final float xc = mCircle.getWidth() / 2;
final float yc = mCircle.getHeight() / 2;
final float x = event.getX();
final float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
mCircle.clearAnimation();
mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
break;
}
case MotionEvent.ACTION_MOVE: {
mPrevAngle = mCurrAngle;
mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
animate(mPrevAngle, mCurrAngle, 0);
break;
}
case MotionEvent.ACTION_UP : {
mPrevAngle = mCurrAngle = 0;
break;
}
}
return true;
}
private void animate(double fromDegrees, double toDegrees, long durationMillis) {
final RotateAnimation rotate = new RotateAnimation((float) fromDegrees, (float) toDegrees,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(durationMillis);
rotate.setFillEnabled(true);
rotate.setFillAfter(true);
mCircle.startAnimation(rotate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Related
My app has two buttons. One for selecting image from the storage and loading it to an ImageView. I do that using Picasso library. The other button is drawing a point on the Canvas. I have attached rotate, scale and move gesture detectors on the Imageview.
The problem here is that right after I draw the point, I want that point to move when I perform the move gesture. Similarly the point should scale up or down when I perform the scale gesture. But the point doesn't move at all.
MainActivity.class
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.almeros.android.multitouch.MoveGestureDetector;
import com.almeros.android.multitouch.RotateGestureDetector;
import com.github.chrisbanes.photoview.PhotoView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 1;
ImageView marker_iv;
DrawImageView iv;
TextView tvFloor;
Button checkpointBt, selectBt;
RelativeLayout rootLayout;
private Matrix mMatrix = new Matrix();
private float mScaleFactor = 1f;
private float mRotationDegrees = 0.f;
private float mFocusX = 0.f;
private float mFocusY = 0.f;
private int mAlpha = 255;
private int mImageHeight, mImageWidth;
private ScaleGestureDetector mScaleDetector;
private RotateGestureDetector mRotateDetector;
private MoveGestureDetector mMoveDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
setListeners();
}
private void initViews() {
iv = findViewById(R.id.main_iv);
tvFloor = findViewById(R.id.floormain_tv);
marker_iv = findViewById(R.id.marker_iv);
checkpointBt = findViewById(R.id.check_bt);
selectBt = findViewById(R.id.select_bt);
rootLayout = findViewById(R.id.root);
mFocusX = rootLayout.getWidth() / 2;
mFocusY = rootLayout.getHeight() / 2;
mScaleDetector = new ScaleGestureDetector(getApplicationContext(), new
ScaleListener());
mRotateDetector = new RotateGestureDetector(getApplicationContext(), new
RotateListener());
mMoveDetector = new MoveGestureDetector(getApplicationContext(), new
MoveListener());
}
private void setListeners() {
iv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mMoveDetector.onTouchEvent(event);
float scaledImageCenterX = (mImageWidth * mScaleFactor) / 2;
float scaledImageCenterY = (mImageHeight * mScaleFactor) / 2;
mMatrix.reset();
mMatrix.postScale(mScaleFactor, mScaleFactor);
mMatrix.postRotate(mRotationDegrees, scaledImageCenterX,
scaledImageCenterY);
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY -
scaledImageCenterY);
ImageView view = (ImageView) v;
view.setImageMatrix(mMatrix);
view.setAlpha(mAlpha);
return true;
}
});
checkpointBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
iv.x = marker_iv.getX() + 45;
iv.y = marker_iv.getY() + 45;
iv.invalidate();
iv.drawRect = true;
}
});
selectBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
if (requestCode == PICK_IMAGE & resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null !=
data) {
Uri selectedImage = data.getData();
Picasso.get().load(selectedImage).noPlaceholder().into(iv);
mImageWidth = iv.getWidth();
mImageHeight = iv.getWidth();
float scaledImageCenterX = (mImageWidth * mScaleFactor) / 2;
float scaledImageCenterY = (mImageHeight * mScaleFactor) / 2;
mMatrix.postScale(mScaleFactor, mScaleFactor);
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY -
scaledImageCenterY);
iv.setImageMatrix(mMatrix);
showTheDialog();
}
}
}
private void showTheDialog() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.floornamedialog);
d.setCancelable(false);
final EditText enteredFloor = d.findViewById(R.id.floor_et);
Button dialogButton = d.findViewById(R.id.floor_bt);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String str = enteredFloor.getText().toString();
tvFloor.setText("Floor Name: " + str);
d.dismiss();
}
});
d.show();
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor(); // scale change since
previous event
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
/* iv.setScaleX(mScaleFactor);
iv.setScaleX(mScaleFactor);*/
return true;
}
}
private class RotateListener extends
RotateGestureDetector.SimpleOnRotateGestureListener {
#Override
public boolean onRotate(RotateGestureDetector detector) {
mRotationDegrees -= detector.getRotationDegreesDelta();
// iv.setRotation(mRotationDegrees);
return true;
}
}
private class MoveListener extends
MoveGestureDetector.SimpleOnMoveGestureListener {
#Override
public boolean onMove(MoveGestureDetector detector) {
PointF d = detector.getFocusDelta();
mFocusX += d.x;
mFocusY += d.y;
/* iv.setX(mFocusX);
iv.setY(mFocusY);*/
return true;
}
}
}
DrawImageView.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;
#SuppressLint("AppCompatCustomView")
public class DrawImageView extends ImageView {
private Paint currentPaint;
public boolean drawRect = false;
public float x;
public float y;
public Bitmap newBitmap;
public Matrix matrix;
public DrawImageView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF00CC00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(60);
}
public void setNewBitmap(Bitmap bmp){
newBitmap = bmp;
}
public Bitmap getNewBitmap(){
return newBitmap;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(drawRect){
canvas.drawPoint(x,y,currentPaint);
//canvas.drawBitmap(newBitmap,new Matrix(),null);
//canvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
}
}
Images-
This is right after I selected an image from gallery and load it into imageview
This is right after I press the 'Add checkpoint button'. The green dot appears
This is when I moved the image. The dot stays there. I want it to move with the bitmap
enter image description here
package test;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.ImageSource;
import java.util.ArrayList;
import java.util.List;
import common.PinView;
public class RoomFragment extends Fragment{
PinView imageView;
LinearLayout layoutFooter;
List<PointF> pinList = new ArrayList<PointF>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.room_fragment_layout, container, false);
//footer action bar
layoutFooter = (LinearLayout) rootView.findViewById(R.id.footer_room);
layoutFooter.setVisibility(LinearLayout.INVISIBLE);
//End footer action bar
//image plane and pin
imageView = (PinView) rootView.findViewById(R.id.plane);
imageView.setImage(ImageSource.resource(R.drawable.plane));
imageView.setZoomEnabled(false);
pinList.add(new PointF(100f, 1200f));
pinList.add(new PointF(400f, 1200f));
pinList.add(new PointF(1000f, 1200f));
imageView.setPins(pinList);
//imageView.setPin(new PointF(800f, 1200f));
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
layoutFooter.setVisibility(LinearLayout.INVISIBLE);
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
Toast.makeText(getContext(), motionEvent.getX() + " | " + motionEvent.getY(), Toast.LENGTH_SHORT).show();
layoutFooter.setVisibility(LinearLayout.VISIBLE);
}
imageView.setPin(new PointF(motionEvent.getX(), motionEvent.getY()));
return false;
}
});
//End image plane and pin
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
package common;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.util.List;
import product.dm.com.dm.R;
public class PinView extends SubsamplingScaleImageView {
private PointF sPin;
private Bitmap pin;
private List<PointF> pinList;
public PinView(Context context) {
this(context, null);
}
public PinView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
}
public void setPin(PointF sPin) {
this.sPin = sPin;
initialise();
invalidate();
}
public void setPins(List<PointF> pinList){
this.pinList = pinList;
initialise();
}
public PointF getPin() {
return sPin;
}
private void initialise() {
float density = getResources().getDisplayMetrics().densityDpi;
pin = BitmapFactory.decodeResource(this.getResources(), R.drawable.pin_red);
float w = (density/420f) * pin.getWidth();
float h = (density/420f) * pin.getHeight();
pin = Bitmap.createScaledBitmap(pin, (int)w, (int)h, true);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isReady()) {
return;
}
Paint paint = new Paint();
paint.setAntiAlias(true);
if (sPin != null && pin != null) {
PointF vPin = sourceToViewCoord(sPin);
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paint);
}
for(int i=0;i<pinList.size();i++){
Paint paints = new Paint();
paint.setAntiAlias(true);
PointF vPin = sourceToViewCoord(pinList.get(i));
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paints);
}
}
}
Trying to get the ball where it moves back and forth across the screen (left-right).
I tried using the draw function to update the ball position using if statements
x += speed_x;
y += speed_y;
canvas.drawCircle(x, y, 20, paint);
if (x == 0)
speed_x=-1;
if (x == getHeight())
speed_x=1;
if (y == 0)
speed_y = -1;
if (y == getWidth())
speed_y = 1;
invalidate();
This did not work.
**game.java*
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;
public class GameWorld extends SurfaceView implements Runnable {
boolean isRunning;
GameObject obj;
SurfaceHolder holder;
Canvas canvas;
Thread gameThread;
Paint paint;
private Context mContext;
int x = -1;
int y = -1;
int speed_x=1, speed_y=1;
private int xVelocity = 10;
private int yVelocity = 5;
private Handler h;
private final int FRAME_RATE = 30;
public GameWorld(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = new Runnable() {
#Override
public void run() {
invalidate();
}
};
public GameWorld(Context context){
super(context);
isRunning=true;
obj=new GameObject(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),200,300);
paint=new Paint();
gameThread= new Thread(this);
gameThread.start();
holder=getHolder();
}
public void run(){
while(isRunning){
if(!holder.getSurface().isValid()){
continue;
}
update();
draw();
}
}
private void update(){
obj.update();
}
private void draw(){
canvas=holder.lockCanvas();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
obj.draw(canvas);
canvas.drawColor(Color.WHITE);
x+=speed_x;
y+=speed_y;
canvas.drawCircle(x, y, 20, paint);
if(x==0)
speed_x=-1;
if(x== getHeight())
speed_x=1;
if(y==0)
speed_y=-1;
if(y==getWidth())
speed_y=1;
invalidate();
holder.unlockCanvasAndPost(canvas);
}
public boolean onTouchEvent(MotionEvent event){
obj.jump();
return super.onTouchEvent(event);
}
}
**main:**
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameWorld(this));
}
}
**gameobject.java**
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class GameObject {
int x,y;
int velY;
int width, height;
boolean jump;
Bitmap bitmap;
final int GRAVITY =2;
public GameObject(Bitmap bitmap, int x, int y){
this.x=x;
this.y=y;
this.width=bitmap.getWidth();
this.height=bitmap.getHeight();
this.bitmap=bitmap;
velY=0;
jump=false;
}
public void update(){
//handles input
if (jump){
velY=-30;
}
//add gravity
velY+=GRAVITY;
y+=velY;
//POSITION
if(y>300){
y=300;
velY=0;
}
jump=false;
}
public void jump(){
jump=true;
}
Paint paint = new Paint();
public void draw(Canvas canvas){
canvas.drawBitmap(bitmap,x,y,null);
int x=5; //ball
boolean game = true;
// while(game = true)
// {
int maxx = canvas.getWidth();
if (x <= maxx)
{
paint.setColor(Color.WHITE);
canvas.drawCircle(x, 305, 10, paint);
x= (x+2);
}
///else{
// x= (x-2);
// paint.setColor(Color.WHITE);
// canvas.drawCircle(x, 305, 10, paint);
// game = false;
//}
// }
}
public void moveball()
{
x= (x-2);
}
}
Here is my version of a ball moving based on the swipes it recives
import android.app.Activity;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.View;
public class BouncingBallActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View boundcingBallView = new BouncingBallView(this);
setContentView(boundcingBallView);
}
}
Here is the actual view that will make the ball
package com.example.bouncingball;
import java.util.Formatter;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class BouncingBallView extends View {
private int xMin=0,xMax,yMin=0,yMax;
private float ballRadius = 80,ballX = ballRadius+20, ballY= ballRadius+40,ballSpeedX=5,ballSpeedY=3,previousX,previousY;
private RectF ballBounds;
private Paint paint;
private StringBuilder statusmsg = new StringBuilder();
private Formatter formatter = new Formatter(statusmsg);
public BouncingBallView(Context context) {
super(context);
ballBounds = new RectF();
paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setHinting(Paint.HINTING_ON);
paint.setPathEffect(new DashPathEffect(new float[] {1,1}, 0));
paint.setTypeface(Typeface.MONOSPACE);
paint.setTextSize(16);
this.setFocusableInTouchMode(true);
}
#Override
protected void onDraw(Canvas canvas) {
ballBounds.set(ballX-ballRadius , ballY-ballRadius,ballX+ballRadius,ballY+ballRadius);
paint.setColor(Color.GREEN);
canvas.drawOval(ballBounds, paint);
paint.setColor(Color.BLACK);
canvas.drawText(statusmsg.toString(), 10, 30,paint);
update();
invalidate();
}
private void update() {
ballX +=ballSpeedX;
ballY+=ballSpeedY;
if(ballX+ballRadius> yMax) {
ballSpeedX =-ballSpeedX;
ballX = xMax -ballRadius;
}
else if(ballX - ballRadius < xMin) {
ballSpeedX = -ballSpeedX;
ballX = xMin+ballRadius;
}
if(ballY + ballRadius > yMax) {
ballSpeedY = -ballSpeedY;
ballY = yMax-ballRadius;
}
else if (ballY - ballRadius < yMin) {
ballSpeedY = -ballSpeedY;
ballY = yMin+ballRadius;
}
statusmsg.delete(0, statusmsg.length());
formatter.format("Ball#(%3.0f,%3.0f),Speed=(%2.0f,%2.0f)", ballX, ballY,ballSpeedX, ballSpeedY);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
xMax = w-1;
yMax = h-1;
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_RIGHT:
ballSpeedX++;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
ballSpeedX--;
break;
case KeyEvent.KEYCODE_DPAD_UP:
ballSpeedY--;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
ballSpeedY++;
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
ballSpeedX = 0;
ballSpeedY = 0;
break;
case KeyEvent.KEYCODE_A:
float maxRadius = (xMax > yMax) ? yMax / 2* 0.9f : xMax / 2 * 0.9f;
if(ballRadius < maxRadius)
ballRadius*=1.05;
break;
case KeyEvent.KEYCODE_Z:
if(ballRadius>20){
ballRadius *=0.95;
}
break;
}
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float currentX=event.getX();
float currentY = event.getY();
float deltaX,deltaY;
float scalingFactor = 5.0f / ((xMax > yMax) ? yMax : xMax);
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
deltaX = currentX - previousX;
deltaY = currentY - previousY;
ballSpeedX += deltaX*scalingFactor;
ballSpeedY += deltaY*scalingFactor;
}
previousX = currentX;
previousY = currentY;
return true;
}
}
I followed the tutorial from here https://github.com/vivekrk/SurfaceView-Sample and modified it to the code below.
Every time I press on the button to change the color The entire color including the the line which was already present on the view changes.I want only the new line to change its color .
How do I do that?
I am a noob in Android and any help would be greatly appreciated.
Thanks in Advance.
CanvasView.java
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
private static final float STROKE_WIDTH = 8;
private UIThread uiThread;
private Path mPath;
public static Paint mPaint;
private Path oldPath;
private DrawableObject drawableObject = null;
private float mX;
private float mY;
private float TOUCH_TOLERANCE = 8;
private RectF dirtyRect;
private int mMode = Constants.FREE_DRAWING;
private ArrayList<DrawableObject> objectsToDraw;
public static int colorofpaint;
public CanvasView(Context context) {
super(context);
getHolder().addCallback(this);
objectsToDraw = new ArrayList<DrawableObject>();
mPath = new Path();
}
public void clearCanvas() {
mPath.reset();
}
public void setDrawingMode(int drawingMode) {
mMode = drawingMode;
}
#Override
public void onDraw(Canvas canvas) {
setPaintProperties();
if (canvas != null) {
canvas.drawColor(Color.WHITE);
synchronized (objectsToDraw) {
for (DrawableObject drawableObject : objectsToDraw) {
drawableObject.draw(canvas);
}
}
}
}
public void stopUIThread() {
uiThread.setRunning(false);
}
private void setPaintProperties() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
//mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(STROKE_WIDTH);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
oldPath = mPath;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (mMode) {
case Constants.FREE_DRAWING:
drawableObject = new FreeDrawing(mPath, mPaint);
if (colorofpaint==1) {
mPaint.setColor(Color.GREEN);
}
if (colorofpaint==2) {
mPaint.setColor(Color.RED);
}
if (colorofpaint==3) {
mPaint.setColor(Color.BLUE);
}
if (colorofpaint==4) {
mPaint.setColor(Color.YELLOW);
}
if (colorofpaint==5) {
mPaint.setColor(Color.CYAN);
}
if (colorofpaint==6) {
mPaint.setColor(Color.BLACK);
}
if (colorofpaint==7) {
mPaint.setColor(Color.MAGENTA);
}
break;
default:
break;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
synchronized (objectsToDraw) {
objectsToDraw.add(drawableObject);
}
mPath.moveTo(x, y);
mX = x;
mY = y;
break;
case MotionEvent.ACTION_MOVE:
switch (mMode) {
case Constants.FREE_DRAWING:
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;
}
break;
}
break;
case MotionEvent.ACTION_UP:
switch (mMode) {
case Constants.FREE_DRAWING:
mPath.moveTo(x, y);
break;
}
break;
}
return true;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
uiThread = new UIThread(this);
uiThread.setRunning(true);
uiThread.start();
}
public void restoreOldPath() {
mPath = oldPath;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
uiThread.setRunning(false);
}
public RectF getDirtyRect() {
if(dirtyRect == null) {
dirtyRect = new RectF();
}
return dirtyRect ;
}
}
UIThread .java
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class UIThread extends Thread {
private static boolean toRun = false;
private CanvasView canvasView;
private SurfaceHolder surfaceHolder;
public UIThread(CanvasView canvasView) {
this.canvasView = canvasView;
surfaceHolder = canvasView.getHolder();
}
public boolean isThreadRunning() {
return toRun;
}
public void setRunning(boolean run) {
toRun = run;
}
#Override
public void run() {
Canvas c;
while (toRun) {
c = null;
try {
c = surfaceHolder.lockCanvas(null);
canvasView.onDraw(c);
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
FreeDrawing .java
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
public class FreeDrawing extends DrawableObject {
private Path mPath;
private Paint mPaint;
public FreeDrawing(Path path, Paint paint) {
mPath = path;
mPaint = paint;
}
#Override
public void draw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
}
}
DrawableObject .java
import android.graphics.Canvas;
public abstract class DrawableObject {
abstract public void draw(Canvas canvas);
}
Constants .java
public class Constants {
// XXX:Drawing modes
public static final int FREE_DRAWING = 1000;
public static final int LINE_DRAWING = 1001;
public static final int RECT_DRAWING = 1002;
public static final int SELECT = 1003;
}
SurfaceViewSampleActivity .java
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class SurfaceViewSampleActivity extends Activity {
/** Called when the activity is first created. */
private CanvasView view;
private static final int CLEAR = 100;
private FrameLayout surfaceViewFrame;
private RadioGroup mode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceViewFrame = (FrameLayout) findViewById(R.id.surfaceviewFrame);
view = new CanvasView(this);
surfaceViewFrame.addView(view, 0);
CanvasView.colorofpaint=6;
view.setDrawingMode(Constants.FREE_DRAWING);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CanvasView.colorofpaint=2;
// view.setDrawingMode(Constants.FREE_DRAWING);
}
});
Button b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CanvasView.colorofpaint=3;
view.setDrawingMode(Constants.FREE_DRAWING);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CLEAR, 0, "Clear");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CLEAR:
view.clearCanvas();
break;
}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Toast.makeText(getApplicationContext(), "onConfigurationChanged", Toast.LENGTH_SHORT).show();
}
}
Im making a game on android where theres an image and u have to drag and move it. however as i drag it several images are created on the path where the image is dragged. please look at my code and help
package com.saad.alien;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class Game extends Activity implements OnTouchListener {
CustomView Cview;
float x, y, left = 0, top = 0, right = 0, bottom = 0;
float dx, dy;
Bitmap man;
int done = 0;
RectF rman = new RectF(50, 50, 150, 150);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Cview = new CustomView(this);
Cview.setOnTouchListener(this);
x = 50;
y = 600;
dx = dy = 0;
man = BitmapFactory.decodeResource(getResources(), R.drawable.man);
setContentView(Cview);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Cview.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Cview.resume();
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// x = event.getX();
// y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dx = event.getX();
dy = event.getY();
float length = x + man.getWidth();
float height = y + man.getHeight();
if (dx > x && dx < length && dy > y && dy < height) {
done = 1;
}
break;
case MotionEvent.ACTION_MOVE:
if (done == 1) {
x = event.getX();
y = event.getY();
}
break;
case MotionEvent.ACTION_UP:
if (done == 1) {
x = event.getX();
y = event.getY();
done = 0;
}
break;
}
return true;
}
public class CustomView extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public CustomView(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas can = ourHolder.lockCanvas();
left = x;
right = (x + man.getWidth());
top = y;
bottom = (y + man.getHeight());
rman.set(left, top, right, bottom);
can.drawBitmap(man, null, rman, null);
ourHolder.unlockCanvasAndPost(can);
}
}
}
}
You need to clear the canvas at each frame before drawing on it.
For instance, something like:
Canvas.drawColor(Color.BLACK)