Android On Touch - android

I have been trying to make a program draw circles as I touch the screen with no luck, can anyone please tell me how I can do this? or GOOD tutorial that shows me how... I keep getting errors in my code
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Math;
public class GameView extends View{
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public GameView(Context context, float x, float y, int r) {
super(context);
setFocusable(true);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
GameActivity.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
public class GameActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.my_view);
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(final View v, MotionEvent e) {
final float x = e.getX();
final float y = e.getY();
final Handler handler = new Handler()
{
public void handleMessage(Message msg) {
}
};
Thread graphicThread = new Thread()
{
public void run() {
try {
//Do the drop
FrameLayout flView = (FrameLayout) v;
GameView gm = new GameView(getParent(), x,y,25);
flView.addView(gm);
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
boolean isRunning=true;
graphicThread.start();
return true;
}
});
}
}

You shouldn't be using getParent() in your activity if it's not a child Activity.
Use this instead:
GameView gm = new GameView(this, x, y, 25);

As the NPE question is already answered, I want to provide an answer for the tutorial question. I have written a series (which is partly updated) which you can find here: I have written a tutorial about 2d graphics for a game. Read this: http://www.droidnova.com/2d-tutorial-series

Related

2 or more rectangles with Canvas or using CustomDrawableView class android

I want more Rectangles in the same Canvas, so I show them in the same activity.
But using a special class (CustomDrawableView) when I add the second SetContentView(my_second_Drawable) my activity is full white.
Instead, using my_canvas.drawRect(x,y,width,height,my_paint) none rectangle appears.
I search into Web but i don't find anything.
Can you help me please?
Sorry for my English.
package com.example.prova.shaperectprove;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private LinearLayout myLayout,redLayout,greenLayout;
ShapeDrawable myshape;
CustomDrawableView greenDrawableView;
CustomDrawableView redDrawableView;
CustomDrawableView blueDrawableView;
Canvas mycanvas = new Canvas();
final private static String str = "Green";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
myLayout = new LinearLayout(getApplicationContext());
myLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 50));
myLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams myLLP = new LinearLayout.LayoutParams(200, 50);
LinearLayout.LayoutParams myLLP2 = new LinearLayout.LayoutParams(200, 50);
redLayout = new LinearLayout(getApplicationContext());
redLayout.setLayoutParams(myLLP2);
redLayout.setOrientation(LinearLayout.HORIZONTAL);
greenLayout = new LinearLayout(getApplicationContext());
greenLayout.setLayoutParams(myLLP);
greenLayout.setOrientation(LinearLayout.HORIZONTAL);
//dichiarazione
greenDrawableView = new CustomDrawableView(this);
redDrawableView = new CustomDrawableView(this);
blueDrawableView = new CustomDrawableView(this);
if (greenDrawableView.isClickable()) {
Log.i("Cliccabile", "TRUE_clickable");
}
greenDrawableView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
MyDialogGreen dialogGreen = new MyDialogGreen();
dialogGreen.show(fm, str);
}
});
greenDrawableView.changeSize(10,10, 210, 60); //left,top,right,bottom
redDrawableView.changeSize(210, 10, 420, 60);
redDrawableView.changeColor(0xFFC12727);
greenLayout.addView(greenDrawableView);
redLayout.addView(redDrawableView);
myLayout.addView(greenLayout);
myLayout.addView(redLayout);
setContentView(myLayout);
}
}
package com.example.prova.shaperectprove;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.text.Layout;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.RelativeLayout;
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
int x,y,width,height,drawColor = 0xFF1A9316;
public CustomDrawableView(Context context) {
super(context);
x = 20;
y = 20;
width = 200;
height = 60;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(drawColor);
mDrawable.setBounds(x, y, width, height); /
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
protected void changeColor(int newColor) {
drawColor = newColor;
}
protected int getLenght()
{
return width-x; //right-left
}
protected int getHight()
{
return height-y; //bottom-top
}
protected int mygetLeft()
{
return x;
}
protected int mygetTop()
{
return y;
}
protected int mygetRight()
{
return width;
}
protected int mygetBottom()
{
return height;
}
protected void changeSize(int x, int y,int width, int height){
mDrawable.setBounds(x, y, width, height);
invalidate();
}
}

Move an object using accelerometer

Hello :) I created a yellow canvas with a ball on it, now i'm trying to move the ball but I don't know how, it's the first time i'm using an accelerometer and it's my first time using canvas and draw.. So can you help me moving it?
Here is my code so far:
package com.example.theball;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.view.Display;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private int c = Color.YELLOW;
private Canvas g;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
draw();
}
#SuppressWarnings("deprecation")
public void draw ()
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getHeight();
int height = display.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
g = new Canvas(bitmap);
g.drawColor(c);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
g.drawCircle(50, 10, 25, paint);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
setContentView(layout);
}
public void onSensorChanged(SensorEvent event)
{
}
}
SOLVED: here is the new code, thanks to someone here from stackoverflow:
package com.example.theball;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
#SuppressWarnings("deprecation") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
}
}
public class AnimatedView extends ImageView {
static final int width = 50;
static final int height = 50;
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
mDrawable.draw(canvas);
invalidate();
}
}
}

How to let the diagram drawed by canvas produce onclick event

I have an imageView and I draw the diagram in imageView according to the coordinate array. Every diagram has an onclick event.
Activity.java
package com.example.floorexhibitiontest;
import com.floor.DrawView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class HallActivity extends Activity {#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hall);
}
float[][][] points = new float[][][] {
{
{213,264},
{247,232},
{345,338},
{310,371}
},
{
{171,305},
{205,272},
{302,373},
{267,406}
},
{
{571,320},
{606,320},
{606,428},
{571,428}
}
};
LinearLayout layout = (LinearLayout)findViewById(R.id.root);
final DrawView draw = new DrawView(this,points);
layout.addView(draw);
}
DrawView.java
package com.floor;
import com.example.floorexhibitiontest.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.Paint.Style;
import android.graphics.Shader.TileMode;
import android.graphics.Shader;
import android.util.DisplayMetrics;
import android.view.View;
public class DrawView extends View{
private float[][][] points = null;
DisplayMetrics metric = new DisplayMetrics();
public DrawView(Context context,float[][][] p) {
super(context);
metric = context.getApplicationContext().getResources().getDisplayMetrics();
points = p;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float density=metric.density;
for(int i = 0; i < points.length; i++){
Paint p = new Paint();
p.setAntiAlias(true);
p.setColor(Color.BLUE);
Path path=new Path();
path.moveTo(points[i][0][0] / density, points[i][0][1] / density);
path.lineTo(points[i][1][0] / density, points[i][1][1] / density);
path.lineTo(points[i][2][0] / density, points[i][2][1] / density);
path.lineTo(points[i][3][0] / density, points[i][3][1] / density);
path.close();
p.setStyle(Style.STROKE);
canvas.drawPath(path, p);
}
}
}
At present effect:
How to let each rectangular drawed produce their own onclick event?
There is an ImageView in Layout file. My purpose is to put the graphics paint on the ImageView. But the result is ImageView can display. The painted graphics can not display. If I hide
ImageView, the image can display.
Ask everyone’s help. Thanks in advice.
Try smth like this:
public boolean onTouch(View v, MotionEvent event) {
if((event.getX(0)>=x_coord) &&
(event.getY(0)>=y_coord) &&
( event.getX(0)<=x_coord + your_rectangle_width) &&
(event.getY(0)<=y_coord + your_rectangle_heigth))
{
//rectangle selected
}
return true;
}
Or use in onTouch() your actual coordinates from points[] array

SurfaceView showing blank white screen

I am trying to draw an oval to the screen but all I am getting is a blank white canvas. Not only am I unsure whether I am drawing the oval correctly, but also am getting nothing to the screen. Does anyone know why this is happening, I think the problem is that it isnt getting to the drawing section of the thread...
package hidden;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.shapes.OvalShape;
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.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
public class Surface extends Activity implements OnTouchListener
{
SurfaceView v;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
setRequestedOrientation(1);
v = new SView(this);
v.setOnTouchListener(this);
v.setZOrderOnTop(true);
setContentView(v);
}
public class SView extends SurfaceView implements Runnable
{
Thread t1 = null;
SurfaceHolder holder;
boolean isItOk = false;
public SView(Context context)
{
super(context);
holder = getHolder();
holder.setFormat(PixelFormat.TRANSPARENT);
}
public void run()
{
while(isItOk)
{
if(!holder.getSurface().isValid())
{
continue;
}
Canvas c = holder.lockCanvas();
Paint p = new Paint();
p.setColor(Color.BLUE);
//OvalShape oval = new OvalShape();
//oval.draw(c, p);
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
float leftx = 20;
float topy = 20;
float rightx = 50;
float bottomy = 100;
RectF ovalBounds = new RectF(leftx, topy, rightx, bottomy);
c.drawOval(ovalBounds, paint);
holder.unlockCanvasAndPost(c);
}
}
public void pause()
{
isItOk = false;
while(true)
{
try
{
t1.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
break;
}
t1 = null;
}
public void resume()
{
isItOk = true;
t1 = new Thread(this);
t1.start();
}
}
public boolean onTouch(View arg0, MotionEvent arg1)
{
return false;
}
}

Problem with SurfaceView and its holder

Hi All
I tried to use SurfaceView, but the view appeared black and nothing painted
Here My code
package com.samples;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
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.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class Galary extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GalaryView(this));
}
private static class GalaryView extends SurfaceView implements Callback {
private SurfaceHolder surfaceHolder;
public GalaryView(Context context) {
super(context);
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Effects effects= new Effects(surfaceHolder, this);
effects.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
}
and the second file
package com.samples;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class Effects extends Thread {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Bitmap bitmap1;
private Path mPath;
private Bitmap bitmap2;
private Paint paint;
public Effects(SurfaceHolder surfaceHolder, SurfaceView surfaceView) {
this.surfaceView = surfaceView;
this.surfaceHolder = surfaceHolder;
this.mPath = new Path();
bitmap1 = BitmapFactory.decodeResource(surfaceView.getContext()
.getResources(), R.drawable.qina1);
bitmap2 = BitmapFactory.decodeResource(surfaceView.getContext()
.getResources(), R.drawable.qina2);
paint= new Paint();
}
#Override
public void run() {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
for (int i = 1; i < 100; i++) {
canvas.drawBitmap(bitmap1, 0, 0, null);
canvas.save();
canvas.translate(0, 0);
mPath.reset();
canvas.clipPath(mPath);
int ovalWidth = (int) (surfaceView.getWidth() * (i / 100.0));
int ovalHeight = (int) (surfaceView.getHeight() * (i / 100.0));
int ovalX = (surfaceView.getWidth() - ovalWidth) / 2;
int ovalY = (surfaceView.getHeight() - ovalHeight) / 2;
mPath.addOval(new RectF(ovalX, ovalY, ovalWidth + ovalX, ovalHeight
+ ovalY), Path.Direction.CCW);
canvas.clipPath(mPath, Region.Op.REPLACE);
canvas.drawBitmap(bitmap2, 0, 0, paint);
canvas.restore();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Please could you tell me what is the problem?
Thanks a lot
Have a onDraw() inside the class "GalaryView" and draw your graphics there. From the run() of the thread call the onDraw(). This post has some sample code Android:Crash: Binary XML file line : Error inflating class (using SurfaceView) . Hope this helps !

Categories

Resources