I have Activity.java and PaintView extends View implements OnTouchListener interface. In this program I have to click on buttons (pink and blue background button) and select a shape and drag into the view area.
I need help I have been trying last few days.
MainActivity.java
package com.easyway2win;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button butnPink,butnBlue;
public PaintView paintView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
butnPink = (Button)findViewById(R.id.pinkColor);
butnBlue = (Button)findViewById(R.id.blueColor);
View paintView = (View)findViewById(R.id.view1);
}
public void clickMe(View view){
int intColor = 0;
String hexColor = null;
switch(view.getId()){
case R.id.pinkColor:
intColor = getResources().getColor(R.color.pink);
hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Log.d("Hi", "I am pink color code " + hexColor);
break;
case R.id.blueColor:
intColor = getResources().getColor(R.color.blue);
}
PaintView paintView = new PaintView(this);
paintView.setPaintColour(intColor);
}// end [ clickMe method ]
}
package com.easyway2win;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
PaintView.java
public class PaintView extends View implements OnTouchListener{
private Paint paint;
private Path path;
private Bitmap buffer = null;
private Canvas penCanvas = null;
int colour = 0;
public PaintView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
// create the Paint and set its color
paint = new Paint();*/
path = new Path();
}
public PaintView(Context context, AttributeSet attrs ){
super(context, attrs);
}
public PaintView(Context context, AttributeSet attrs, int defStyle/*Context context, Rect rectangle, Paint paint*/) {
super(context,attrs,defStyle);
// this.rectangle = rectangle;
// this.paint = paint;
}
public void setPaintColour(int colour){
paint.setColor(colour);
//Log.d("Hi", "I am in setPaintColour Method" );
}
#Override
protected void onDraw(Canvas canvas) {
/* canvas.drawRect(rectangle,paint);*/
canvas.drawPath(path, paint);
}
#Override
public boolean onTouch(View v, MotionEvent evt) {
int action = evt.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:{
//Toast.makeText(getContext(), "Action Down", Toast.LENGTH_LONG);
//Log.d("Down", "Pointer Down");
break;
}
case MotionEvent.ACTION_POINTER_DOWN : {
Log.d("CV", "Other point down");
break;
}
case MotionEvent.ACTION_POINTER_UP : {
Log.d("CV", "Other point up");
break;
}
case MotionEvent.ACTION_UP : {
Log.d("CV", "Pointer up");
break;
}
}
return true;
}
}
The null pointer exception happens when you try to call methods on the paint object before it has been created. The paint = new Paint(); line needs to be moved earlier in the PaintView constructor, or paint can simply be initialized where it is declared.
public class PaintView extends View implements OnTouchListener{
private Paint paint;
// alternate: private Paint paint = new Paint();
private Path path;
private Bitmap buffer = null;
private Canvas penCanvas = null;
int colour = 0;
public PaintView(Context context) {
super(context);
// create the Paint and set its color
paint = new Paint();*/
// alternate: skip this line and use the alternate above
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
path = new Path();
}
It also looks like the PaintView is never added into your layout. The object is created, but it isn't attached to anything in the UI. If you have a reference to the ViewGroup (LinearLayout, etc.), a new View can be added to it with the addView method. If another View needs to be removed from the layout, use removeView.
Related
I am new to coding and to java and android. I am making an app that has multiple canvas views (where a person can draw lines with their finger) in multiple fragments (requested to be like this). I have managed to get the fragments to work and to draw lines on each canvas. Next, I want to be able to save the lines drawn by the user when the user goes to a different fragment or closes the app and when the user comes back to a fragment, the drawing for that fragment will still be there, and can continue editing it by adding more lines or clear it by hitting Clear, the same should happen for other fragments that should have their respective drawings.
I was previously told about the interface Parcelable and have made some steps to implement it but I am finding it hard to understand what I am doing and having trouble reading in an ArrayList. The error is stating that it is expecting ClassLoader but being provided with an ArrayList (I hope in the right place), and that's if I make the getter static but that creates an error: Non-static field 'paths' cannot be referenced from a static context in the getter in the PaintView class (this controls the drawing). I get a similar static context message for the readArrayList method in the FingerPath class. Once this is figured out, I will need to find out how to bring the relevant, saved drawing back to the canvas when the fragment is opened which I am not sure how, I think when the Bundle isn't equal to null but not sure.
I'll show the code below (right now it is on a test app)
FingerPath class
import android.graphics.Path;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class FingerPath implements Parcelable {
public int color;
public boolean emboss;
public boolean blur;
public int strokeWidth;
public Path path;
public FingerPath(int color, boolean emboss, boolean blur, int strokeWidth, Path path) {
this.color = color;
this.emboss = emboss;
this.blur = blur;
this.strokeWidth = strokeWidth;
this.path = path;
}
protected FingerPath(Parcel in) {
color = in.readInt();
emboss = in.readByte() != 0;
blur = in.readByte() != 0;
strokeWidth = in.readInt();
//line below causing me issues
path = in.readArrayList(PaintView.getPaths());
}
public static final Creator<FingerPath> CREATOR = new Creator<FingerPath>() {
#Override
public FingerPath createFromParcel(Parcel in) {
return new FingerPath(in);
}
#Override
public FingerPath[] newArray(int size) {
return new FingerPath[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(color);
parcel.writeByte((byte) (emboss ? 1 : 0));
parcel.writeByte((byte) (blur ? 1 : 0));
parcel.writeInt(strokeWidth);
//parcel.writeParcelableArray(PaintView.getPaths(), 0);
}
}
PaintView
Controls what happens when the user starts drawing
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
public class PaintView extends View {
public static int BRUSH_SIZE = 10;
public static final int DEFAULT_COLOR = Color.WHITE;
public static int DEFAULT_BG_COLOR = Color.GRAY;
private static final float TOUCH_TOLERANCE = 4;
private float mX, mY;
private Path mPath;
private Paint mPaint;
private ArrayList<FingerPath> paths = new ArrayList<>();
private int currentColor;
private int backgroundColor = DEFAULT_BG_COLOR;
private int strokeWidth;
private boolean emboss;
private boolean blur;
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
public PaintView(Context context) {
this(context, null);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(null);
mPaint.setAlpha(0xff);
mEmboss = new EmbossMaskFilter(new float[] {1, 1, 1}, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
}
//the getter in question
public ArrayList getPaths() {
return paths;
}
public void init(DisplayMetrics metrics) {
int height = metrics.heightPixels;
int width = metrics.widthPixels;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
currentColor = DEFAULT_COLOR;
strokeWidth = BRUSH_SIZE;
}
public void normal() {
emboss = false;
blur = false;
}
public void clear() {
backgroundColor = DEFAULT_BG_COLOR;
paths.clear();
normal();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
mCanvas.drawColor(backgroundColor);
for (FingerPath fp: paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.strokeWidth);
mPaint.setMaskFilter(null);
if (fp.emboss)
mPaint.setMaskFilter(mEmboss);
else if (fp.blur)
mPaint.setMaskFilter(mBlur);
mCanvas.drawPath(fp.path, mPaint);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}
private void touchStart(float x, float y) {
mPath = new Path();
FingerPath fp = new FingerPath(currentColor, emboss, blur, strokeWidth, mPath);
paths.add(fp);
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x-mX);
float dy = Math.abs(y-mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE :
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP :
touchUp();
invalidate();
break;
}
return true;
}
}
Here's an example of a fragment
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class LineLHwFragment extends Fragment {
private PaintView paintView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_line_l_hw, container, false);
paintView = v.findViewById(R.id.lineLPaintView);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
paintView.init(metrics);
setHasOptionsMenu(true);
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
paintView.normal();
return true;
case R.id.clear:
paintView.clear();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("line test", paintView.getPaths());
}
}
This is my first question here! I hope that you can help me!
I'm explain:
I'm trying to develop an app like a paint in android studio to work with Paint,Canvas,and this class...
I have a class call Lienzo.java; This is the code of my class:
package com.example.pedro.paint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.graphics.Path;
/**
* Created by Pedro on 26/02/2018.
*/
public class Lienzo extends View {
//PATH TO DRAW THE LINES
private Path drawPath;
//PAINT DRAWING AND PAINT CANVAS
private Paint drawPaint,canvasPaint;
//COLOR INITIAL
private int paintColor=0xFFFF0000;
//CANVAS
private Canvas drawCanvas;
//CANVAS TO SAVE
private Bitmap canvasBitmap;
public Lienzo(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
private void setupDrawing(){
//CONFIGURATION AREA TO DRAW
drawPath = new Path();
drawPaint=new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(20);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint= new Paint(Paint.DITHER_FLAG);
}
//ASIGN SIZE TO VIEW
#Override
protected void onSizeChanged(int w, int h,int oldw, int oldh){
super.onSizeChanged(w,h,oldw,oldh);
canvasBitmap=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
drawCanvas=new Canvas(canvasBitmap);
}
//PAINT THE VIEW.CALL BY ONTHOUCHEVENT
#Override
protected void onDraw(Canvas canvas){
canvas.drawBitmap(canvasBitmap,0,0,canvasPaint);
canvas.drawPath(drawPath,drawPaint);
}
//REGISTER USER TOUCH
public boolean OnTouchEvent(MotionEvent event)
{
float touchX =event.getX();
float touchY=event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX,touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX,touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX,touchY);
drawCanvas.drawPath(drawPath,drawPaint);
drawPath.reset();
break;
default:
return false;
}
//REPAINT
invalidate();
return true;
}
}
I have no error but I try to paint but do nothing.
This is a copy of an example.The original https://www.youtube.com/watch?v=GAr_agEokr8 works but my code,its equal and dont work.
Anybody knows why?
Thanks and regards!
OnTouchEvent change to onTouchEvent and add #Override
This is my first time using Canvas in Android.
I am creating an app that would display circles at certain positions on the screen one at a time (positions are selected randomly). New circle should be drawn after the previous one was selected/touched, and the previous one should disappear.
I have some ideas about it: to keep an arraylist of Point objects(each object contains x,y coordinate of the centre of the circle) and randomly select one each time the circle is drawn on the screen. So first I am populating an array of points. I also know how to randomly select the element from arraylist.
My biggest confustion is how to connect onDraw and onTouchEvent methods with each other? I know I should check if the circle was selected and only then draw a new circle at the randomly selected position, but I m not sure how to make a call for onDraw() method from the onTouchEvent...
Could you please help with this issue?
My code is below:
package com.example.researcher.heatmap;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* TODO: document your custom view class.
*/
public class MyView extends View {
Paint paint;
ArrayList<Point> points = new ArrayList<>();
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
// Load attributes
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
populateArrayList();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
canvas.drawColor(Color.WHITE);
int i=1; // should be random, will randomize later
for(Point p: points) {
p.x = points.get(i).x;
p.y = points.get(i).y;
canvas.drawCircle(p.x, p.y, 50, paint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
int i=1;
for(Point p: points) {
Canvas canvas = new Canvas();
p.x = points.get(i).x;
p.y = points.get(i).y;
canvas.drawCircle(p.x, p.y, 50, paint);
}
postInvalidate();
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
break;
}
}
postInvalidate();
return true;
}
public void populateArrayList(){
points.clear();
points.add(new Point(120, 120));
points.add(new Point(150, 320));
points.add(new Point(280, 200));
}
}
Thank you Chris for your help! I really appreciate it.
Here is my solution if someone will need it for reference
package com.example.researcher.heatmap;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* TODO: document your custom view class.
*/
public class MyView extends View {
Paint paint;
ArrayList<Point> points = new ArrayList<>();
private int pointsPos = 0; //Which point we will be drawing
public float x;
public float y;
public int radius = 150;
public MyView(Context context) {
super(context);
x = this.getX();
y = this.getY();
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
x = this.getX();
y = this.getY();
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
x = this.getX();
y = this.getY();
init();
}
private void init() {
// Load attributes
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
populateArrayList();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
canvas.drawColor(Color.WHITE);
canvas.drawCircle(points.get(pointsPos).x, points.get(pointsPos).y, radius, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
//Check if the point press is within the circle
if(contains(event, points.get(pointsPos))){
Random r = new Random(System.nanoTime());
pointsPos = r.nextInt(points.size());; //between 0 and points.length
postInvalidate();
}
case MotionEvent.ACTION_CANCEL: {
break;
}
}
postInvalidate();
return true;
}
private boolean contains(MotionEvent event, Point point) {
float xTouch = event.getX();
float yTouch = event.getY();
if ((xTouch - point.x) * (xTouch - point.x) + (yTouch - point.y) * (yTouch - point.y) <= radius * radius) {
return true;
}
else {
return false;
}
}
public void populateArrayList(){
points.clear();
points.add(new Point(220, 1020));
points.add(new Point(550, 320));
points.add(new Point(780, 500));
}
}
Class var
private int state = 0 //0 normal, 1 new circle
private int pointPos = 0; //Which point we will be drawing
onDraw was overwriting the x/y of all your other points
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
canvas.drawColor(Color.WHITE);
if(state == 1){
pointPos = random(); //between 0 and points.length
state = 0;
}
canvas.drawCircle(points.get(pointsPos).x, points.get(pointsPos).y, 50, paint);
}
onTouchEvent: Drawing should only be done on the ondraw, use flags/states to keep track of what you should be doing on the next draw call
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//Though these days this is usually done on the up event
//Check if the point press is within the circle
if(contains(event, points.get(pointPos))){
state = 1;
postInvalidate();
}
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
break;
}
}
postInvalidate();
return true;
}
I have a class called OurView. I have 3 Buttons that call moveImage() and pass it two numbers depending on which Button it is.
moveImage() is supposed to change the value of xCoord and yCoord, which it seems to do. When xCoord and yCoord are printed from moveImage() they display the correct values.
But when printed from delay() or doDraw() they display the original value of 500.
Am I doing something incorrect that causes the variables to not be updated?
Here is the class OurView:
package com.thatoneprogrammerkid.gameminimum;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class OurView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Handler handler = new Handler();
private Bitmap testimg;
private int xCoord = 500;
private int yCoord = 500;
int xPos;
int yPos;
public OurView(Context context) {
super(context);
init();
}
public OurView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public OurView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
holder = getHolder();
holder.addCallback(this);
testimg = BitmapFactory.decodeResource(getResources(),R.drawable.testimg);
}
void moveImage(int xChange, int yChange) {
this.xCoord = this.xCoord + xChange;
this.yCoord = this.yCoord + yChange;
System.out.println("Move Image");
printCoords();
}
void printCoords() {
System.out.println(xCoord);
System.out.println(yCoord);
}
void delay() {
System.out.println("Delay");
printCoords();
handler.postDelayed(new Runnable() {
public void run() {
Canvas canvas = getHolder().lockCanvas();
System.out.println("Run");
printCoords();
if(canvas != null){
synchronized (getHolder()) {
doDraw(canvas, xCoord, yCoord);
}
holder.unlockCanvasAndPost(canvas);
}
}
}, 33);
}
void doDraw(Canvas canvas, int x, int y) {
xPos = this.xCoord + (testimg.getWidth()/2);
yPos = this.yCoord + (testimg.getHeight()/2);
System.out.println("Draw");
printCoords();
canvas.drawARGB(255, 55, 255, 255);
canvas.drawBitmap(testimg, x, y, null);
delay();
}
#Override
public void surfaceCreated(final SurfaceHolder holder) {
delay();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
}
Here is the class the handles the button presses:
package com.thatoneprogrammerkid.gameminimum;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class SurfaceViewExample extends Activity {
OurView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new OurView(this);
setContentView(R.layout.activity_surface_view_example);
}
public void arrowPressed(View view) {
switch (view.getId()) {
case R.id.arrowLeft:
gameView.moveImage(-1,0);
break;
case R.id.arrowRight:
gameView.moveImage(1,0);
break;
case R.id.arrowUp:
gameView.moveImage(0,1);
break;
}
}
}
EDIT:
To clarify, after pressing the button 10 times the printCoords() in moveImage() displays the following:
510
500
and the printCoords() in all the other locations displays the following:
500
500
If what I guess is right , the reference you use to call moveImage() and delay() are not the same . Maybe you did something like:
ourView = new OurView();
after calling moveImage.
I have been making a paint app for android with the ability to choose different colors.
my task is almost complete. yet there is cetain lag in my app. At start it works fine but after some lines it starts giving straight lines instead of curves and lags in usage....
This is the code for my DrawIt:
package app.paintit;
import java.util.ArrayList;
import java.util.LinkedList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
public class DrawIt extends View{
float x,y;
Paint paint;
int count1=0,count2=0;
ArrayList<Lines> lines = new ArrayList<Lines>();
public int color= 0xFFFFFF;
Lines l;
Path path;
public DrawIt(Context context) {
super(context);
// TODO Auto-generated constructor stub
x=0;y=0;
paint=new Paint();
path = new Path();
paint.setAntiAlias(true);
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
l = new Lines();
l.color = color;
l.xCoordinate = new ArrayList<Float>();
l.xCoordinate.add(event.getX());
l.yCoordinate = new ArrayList<Float>();
l.yCoordinate.add(event.getY());
lines.add(l);
}
else if(event.getAction() == MotionEvent.ACTION_MOVE)
{
l.color = color;
l.xCoordinate.add(event.getX());
l.yCoordinate.add(event.getY());
lines.add(l);
}
invalidate();
return true;
}
});
}
#Override
protected void onDraw(final Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.BLACK);
Lines p,q;
float nowX,nowY,prevX=0,prevY=0;
for(int j=0;j<lines.size();j++){
p = lines.get(j);
Path path1=new Path();
paint.setColor(p.color);
path1.moveTo(p.xCoordinate.get(0), p.yCoordinate.get(0));
for(int i=1;i<p.xCoordinate.size()-1;i++){
float midX=(p.xCoordinate.get(i)+p.xCoordinate.get(i-1))/2;
float midY=(p.yCoordinate.get(i)+p.yCoordinate.get(i-1))/2;
path1.quadTo(p.xCoordinate.get(i-1), p.yCoordinate.get(i-1), midX, midY);
canvas.drawPath(path1, paint);
}
}
}
}
The code for Lines.java which holds the lists that help in maintaining different colors is :
package app.paintit;
import java.util.ArrayList;
import java.util.LinkedList;
import android.graphics.Color;
public class Lines {
ArrayList<Float> xCoordinate;
ArrayList<Float> yCoordinate;
int color;
}
Please help me how to reduce the lag and the straight lines happening after some shapes are drawn perfectly.