Identify triple tap on custom view - android

I want to draw circle, whenever user taps on a custom view, and based on tap count circle color changes.
Single Tap : YELLOW CIRCLE
Double Tap : GREEN CIRCLE
Triple Tap : RED COLOR
Problem is that, i made one custom view that will count tap event based on time, but some time it miss the first tap. which cause the problem in view.
Following code shows all my effort to make above custom view.
TripleTapView
package com.slk.car_rating_app;
import java.util.ArrayList;
import java.util.Date;
import android.annotation.SuppressLint;
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.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
public class TripleTapView extends View {
// Set the tap delay in milliseconds
protected static final long TAP_MAX_DELAY = 500L;
// Radius to capture tap within bound
final static int RADIUS = 30;
// Store all points with tap count
public ArrayList<CustomPoint> point = new ArrayList<CustomPoint>();
// Context to access view
Context context;
Paint paint;
private long thisTime = 0, prevTime = 0;
private boolean firstTap = true, doubleTap = false;;
float stopX, stopY, startX, startY;
RectF area_rect;
TapCounter tapCounter = new TapCounter(TAP_MAX_DELAY, TAP_MAX_DELAY);
public TripleTapView(Context context) {
super(context);
this.context = context;
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(2);
}
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
for (CustomPoint point_temp : point) {
// For changing tap circle color based on tap count
switch (point_temp.count) {
case 1:
paint.setColor(Color.YELLOW);
break;
case 2:
paint.setColor(Color.GREEN);
break;
case 3:
paint.setColor(Color.RED);
break;
}
canvas.drawCircle(point_temp.point.x, point_temp.point.y, 10, paint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
stopX = event.getX();
stopY = event.getY();
if (firstTap) {
addFirstTap();
} else if (doubleTap) {
prevTime = thisTime;
thisTime = new Date().getTime();
if (thisTime > prevTime) {
if ((thisTime - prevTime) <= TAP_MAX_DELAY) {
if (area_rect.contains(stopX, stopY))
doubleTap = false;
else {
addPoint(1);
addFirstTap();
}
} else {
addPoint(1);
firstTap = true;
}
} else {
firstTap = true;
}
} else {
prevTime = thisTime;
thisTime = new Date().getTime();
if (thisTime > prevTime) {
if ((thisTime - prevTime) <= TAP_MAX_DELAY) {
if (area_rect.contains(stopX, stopY)) {
addPoint(3);
firstTap = true;
} else {
addPoint(2);
addFirstTap();
}
} else {
addPoint(2);
firstTap = true;
}
} else {
firstTap = true;
}
}
}
return true;
}
void addPoint(int tapCount) {
point.add(new CustomPoint(new PointF(startX, startY), tapCount));
invalidate();
}
void addFirstTap() {
thisTime = new Date().getTime();
firstTap = false;
doubleTap = true;
startX = stopX;
startY = stopY;
area_rect = new RectF(stopX - RADIUS, stopY - RADIUS, stopX + RADIUS,
stopY + RADIUS);
tapCounter.resetCounter();
}
class TapCounter extends CountDownTimer {
public TapCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
if (doubleTap) {
prevTime = thisTime;
thisTime = new Date().getTime();
if (thisTime > prevTime) {
if ((thisTime - prevTime) <= TAP_MAX_DELAY) {
doubleTap = false;
} else {
addPoint(1);
firstTap = true;
}
} else {
firstTap = true;
}
} else if (!firstTap && !doubleTap) {
prevTime = thisTime;
thisTime = new Date().getTime();
if (thisTime > prevTime) {
if ((thisTime - prevTime) <= TAP_MAX_DELAY) {
addPoint(2);
firstTap = true;
}
} else {
firstTap = true;
}
}
}
#Override
public void onTick(long millisUntilFinished) {
}
public void resetCounter() {
start();
}
}
}
Please help me to fix this issue.

This code will do what you need. I simplified your class.
import java.util.ArrayList;
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.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
public class TripleTapView extends View {
// Set the tap delay in milliseconds
protected static final long TAP_MAX_DELAY = 500L;
// Radius to capture tap within bound
private final static int RADIUS = 30;
// Store all points with tap count
public ArrayList<CustomPoint> _points = new ArrayList<CustomPoint>();
Context _context;
Paint _paint;
TapCounter _tapCounter = new TapCounter(TAP_MAX_DELAY, TAP_MAX_DELAY);
public TripleTapView(Context context) {
super(context);
_context = context;
_paint = new Paint();
_paint.setAntiAlias(true);
_paint.setDither(true);
_paint.setStyle(Paint.Style.FILL);
_paint.setStrokeJoin(Paint.Join.ROUND);
_paint.setStrokeCap(Paint.Cap.ROUND);
_paint.setStrokeWidth(2);
}
#Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
for (CustomPoint point_temp : _points) {
// For changing tap circle color based on tap count
switch (point_temp.count) {
case 1:
_paint.setColor(Color.YELLOW);
break;
case 2:
_paint.setColor(Color.GREEN);
break;
case 3:
_paint.setColor(Color.RED);
break;
}
canvas.drawCircle(point_temp.point.x, point_temp.point.y, 10,
_paint);
}
}
private RectF _lastTapArea;
private int _lastTapCount = 0;
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
_tapCounter.resetCounter();
float x = event.getX();
float y = event.getY();
if (_lastTapArea != null) {
if (_lastTapArea.contains(x, y)) {
if (_lastTapCount < 3) {
_lastTapCount++;
} else {
addPoint(_lastTapArea.centerX(),
_lastTapArea.centerY(), _lastTapCount);
_lastTapCount = 1;
}
} else {
addPoint(_lastTapArea.centerX(), _lastTapArea.centerY(),
_lastTapCount);
_lastTapCount = 1;
_lastTapArea = new RectF(x - RADIUS, y - RADIUS,
x + RADIUS, y + RADIUS);
}
} else {
_lastTapCount = 1;
_lastTapArea = new RectF(x - RADIUS, y - RADIUS, x + RADIUS, y
+ RADIUS);
}
return true;
}
return false;
}
void addPoint(float x, float y, int tapCount) {
_points.add(new CustomPoint(new PointF(x, y), tapCount));
invalidate();
}
class TapCounter extends CountDownTimer {
public TapCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
if (_lastTapArea != null) {
if (_lastTapCount > 0)
addPoint(_lastTapArea.centerX(), _lastTapArea.centerY(),
_lastTapCount);
_lastTapCount = 0;
_lastTapArea = null;
}
}
#Override
public void onTick(long millisUntilFinished) {
}
public void resetCounter() {
start();
}
}
}

Related

detecting touch event on rectangle in android

I Writing a very simple game in android , the game is like touching a shapes (like rectangle,circle,arc...) and for doing this i write a Thread MainGameTread.class:
package com.example.komeil.surfaceview_2;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import java.util.Random;
/**
* Created by Komeil on 04/11/2016.
*/
public class MainGameThread extends Thread {
private boolean running;
private SurfaceHolder surfaceHolder;
private MainGameView mainGameView;
private String shapeType;
private Random rnd;
private int xPos;
private int yPos;
private int radius;
private int left;
private int right;
private int top;
private int bottom;
private int color;
public MainGameThread (SurfaceHolder surfaceHolder,MainGameView mainGameView)
{
super();
this.surfaceHolder = surfaceHolder;
this.mainGameView = mainGameView;
}
public void setRunning(boolean running)
{
this.running = running;
}
#Override
public void run() {
while (running)
{
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder)
{
makeChoose();
mainGameView.onDraw(canvas);
}
}
finally {
if(canvas != null)
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
private void makeChoose()
{
int radius;
rnd = new Random();
switch (rnd.nextInt(2))
{
case 0:
setShapeType("Rectangle");
setColor(Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255)));
setXpos(rnd.nextInt(mainGameView.getWidth()));
setYpos(rnd.nextInt(mainGameView.getHeight()));
setTop(rnd.nextInt(mainGameView.getHeight()));
setBottom(rnd.nextInt(mainGameView.getHeight()));
setLeft(rnd.nextInt(mainGameView.getWidth()));
setRight(rnd.nextInt(mainGameView.getWidth()));
break;
case 1:
setShapeType("Circle");
setColor(Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255)));
setXpos(rnd.nextInt(mainGameView.getWidth()));
setYpos(rnd.nextInt(mainGameView.getHeight()));
radius = rnd.nextInt(mainGameView.getWidth()-getXpos());
setRadius(radius);
break;
// case 2:
// setShapeType("Arc");
// setXpos(rnd.nextInt(mainGameView.getWidth()));
// setYpos(rnd.nextInt(mainGameView.getHeight()));
// break;
}
}
private void setShapeType(String shapeType)
{
this.shapeType = shapeType;
}
private void setColor(int color) {
this.color = color;
}
public int getColor() {
return color;
}
private void setRadius(int radius)
{
this.radius = radius;
}
public int getRadius()
{
return radius;
}
public int getBottom() {
return bottom;
}
public int getLeft() {
return left;
}
public int getRight() {
return right;
}
public int getTop() {
return top;
}
private void setBottom(int bottom) {
this.bottom = bottom;
}
private void setLeft(int left) {
this.left = left;
}
private void setRight(int right) {
this.right = right;
}
private void setTop(int top) {
this.top = top;
}
private void setXpos(int xPos)
{
this.xPos = xPos;
}
public int getXpos()
{
return xPos;
}
private void setYpos(int yPos)
{
this.yPos = yPos;
}
public int getYpos()
{
return yPos;
}
public String getShapeType()
{
return shapeType;
}
}
so when i use for drawing in UI Thread it's work. but when i touching rectangle
it's like nothing happend(i use score and i want update score when rectangle touched) but score not shown in screen and some times show itself and Disappeared very fast.
This below code for my MainGameView.class:
package com.example.komeil.surfaceview_2;
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.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by Komeil on 04/11/2016.
*/
public class MainGameView extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap bmp;
MainGameThread mainGameThread;
private int x;
private Paint paint;
private Paint textWhite;
private int score;
private Rect rect;
private boolean touched;
public MainGameView(Context context) {
super(context);
getHolder().addCallback(this);
mainGameThread = new MainGameThread(getHolder(),this);
setFocusable(true);
paint = new Paint();
textWhite = new Paint();
textWhite.setAntiAlias(true);
textWhite.setColor(Color.WHITE);
textWhite.setTextSize(30);
paint.setAntiAlias(true);
bmp = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mainGameThread.setRunning(true);
mainGameThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mainGameThread.setRunning(false);
while (retry)
{
try {
mainGameThread.join();
retry = false;
}
catch (InterruptedException ex)
{
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GRAY);
if(x<getWidth()-bmp.getWidth())
x+=2;
else
x=0;
canvas.drawBitmap(bmp,x,10,null);
switch (mainGameThread.getShapeType())
{
case "Rectangle":
paint.setColor(mainGameThread.getColor());
canvas.drawRect(mainGameThread.getLeft(),mainGameThread.getTop(),mainGameThread.getRight(),mainGameThread.getBottom(),paint);
break;
case "Circle":
paint.setColor(mainGameThread.getColor());
canvas.drawCircle(mainGameThread.getXpos(),mainGameThread.getYpos(),mainGameThread.getRadius(),paint);
break;
// case "Arc":
// paint.setColor(mainGameThread.getColor());
// canvas.drawArc(mainGameThread.getLeft(),mainGameThread.getRight()
// ,mainGameThread.getTop(),mainGameThread.getBottom(),);
// break;
}
if(touched)
{
canvas.drawText(String.valueOf(score),getWidth()/2,50,textWhite);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
int xEvent = (int)event.getX();
int yEvent = (int)event.getY();
switch (eventAction)
{
case MotionEvent.ACTION_DOWN:
switch (mainGameThread.getShapeType())
{
case "Rectangle":
rect = new Rect(mainGameThread.getLeft(),mainGameThread.getTop(),mainGameThread.getRight(),mainGameThread.getBottom());
if(rect.contains(xEvent,yEvent))
{
touched = true;
score +=1;
}
else
{
touched = false;
}
break;
case "Circle":
break;
case "Arc":
break;
}
break;
case MotionEvent.ACTION_UP:
touched = false;
break;
}
return super.onTouchEvent(event);
}
}
So How i can show score and do i need another thread for score?

Move ball back and forth

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;
}
}

Android Game - FATAL EXCEPTION: Thread-87

I programmed an Android game via this Youtube tutorial, there you can see how the game should look like at the end.
Everything went fine until I added the Gameover Screen. When I start the emulator, the Game runs accordingly, but when I have used up all my lives and the View should change to the Gameover Screen, it only appears for 1 second and then crashes (the game exits).
This is what the LogCat says:
04-05 06:14:22.178: E/AndroidRuntime(1201): FATAL EXCEPTION: Thread-87
04-05 06:14:22.178: E/AndroidRuntime(1201): Process: com.skies.game, PID: 1201
04-05 06:14:22.178: E/AndroidRuntime(1201): java.lang.NullPointerException
04-05 06:14:22.178: E/AndroidRuntime(1201): at com.skies.game.GameView.draw(GameView.java:79)
04-05 06:14:22.178: E/AndroidRuntime(1201): at com.skies.game.GameLoopThread.run(GameLoopThread.java:30)
Here is my GameOverActivity class
package com.skies.game;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GameOverActivity extends Activity implements OnClickListener {
private Button bReplay;
private Button bExit;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameoverscreen);
bReplay = (Button) findViewById(R.id.bReplay);
bExit = (Button) findViewById(R.id.bExit);
bReplay.setOnClickListener(this);
bExit.setOnClickListener(this);
initialize();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bReplay:
Intent newGameScreen = new Intent(this, GameActivity.class);
startActivity(newGameScreen);
this.finish();
break;
case R.id.bExit:
this.finish();
break;
}
}
public int readHighscore() {
SharedPreferences pref = getSharedPreferences("GAME", 0);
return pref.getInt("HIGHSCORE", 0);
}
public void initialize() {
int score = this.getIntent().getExtras().getInt("score");
TextView tvScore = (TextView) findViewById(R.id.tvScore);
tvScore.setText("Your score is: " + Integer.toString(score));
TextView tvHighscore = (TextView) findViewById(R.id.tvHighScore);
tvHighscore.setText("Endless Game Highscore: "
+ Integer.toString(readHighscore()));
}
}
Here is my GameActivity class
package com.skies.game;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
public class GameActivity extends Activity {
private GameView theGameView;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
theGameView = new GameView(this);
setContentView(theGameView);
}
public void onGameOver()
{
compareScore();
Intent theNextIntent = new Intent (getApplicationContext(), GameOverActivity.class);
theNextIntent.putExtra("score", theGameView.getScore());
startActivity(theNextIntent);
this.finish();
}
public int readHighscore()
{
SharedPreferences pref = getSharedPreferences("GAME", 0);
return pref.getInt("HIGHSCORE", 0);
}
public void writeHighscore(int highscore)
{
SharedPreferences pref = getSharedPreferences("GAME", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("HIGHSCORE", highscore);
editor.commit();
}
public void compareScore()
{
if(theGameView.getScore() > readHighscore())
{
writeHighscore(theGameView.getScore());
}
}
}
and here my GameView class
package com.skies.game;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
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.graphics.Typeface;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private List<Sprite> spriteList = new ArrayList<Sprite>();
private List<Integer> spriteListNum = new ArrayList<Integer>();
private SurfaceHolder surfaceHolder;
private Bitmap bmp;
private Bitmap livesPicture;
private GameLoopThread theGameLoopThread;
private boolean createSprites = true;
private long lastClick;
private int currentColorNum;
private int lives = 4;
private int score = 0;
private Paint paintRed, paintBlue, paintGreen, paintYellow;
private Paint currentColor;
private String scoreString;
private String livesString;
private float density;
private GameActivity theGameActivity= new GameActivity();
public GameView(Context context) {
super(context);
livesPicture = BitmapFactory.decodeResource(getResources(),
R.drawable.lives);
Random rnd = new Random();
theGameActivity = (GameActivity) context;
setColors();
currentColorNum = rnd.nextInt(4);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
}
#Override
public void draw(Canvas canvas) {
canvas.drawColor(Color.DKGRAY);
if (createSprites == true) {
initialSprites();
}
for (Sprite sprite : spriteList) {
sprite.draw(canvas);
}
if (currentColorNum == 0) {
drawLines(paintBlue, canvas);
} else if (currentColorNum == 1) {
drawLines(paintRed, canvas);
} else if (currentColorNum == 2) {
drawLines(paintGreen, canvas);
} else if (currentColorNum == 3) {
drawLines(paintYellow, canvas);
}
final int fontSize = (int) (25 * density);
int yTextPos = (int) (25 * density);
Typeface font = Typeface.create("Arial", Typeface.NORMAL);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTypeface(font);
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
scoreString = String.valueOf(score);
int x = (canvas.getWidth() * 5 / 7);
final String text = "Score: " + scoreString;
canvas.drawText(text, x, yTextPos, paint);
drawLives(canvas, paint);
}
private void createSprite(int index) {
Bitmap bmp = null;
switch (index) {
case 0:
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.alienspriteblue);
break;
case 1:
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.alienspritered);
break;
case 2:
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.alienspritegreen);
break;
case 3:
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.alienspriteyellow);
break;
}
Sprite sprite = new Sprite(this, bmp);
spriteList.add(sprite);
spriteListNum.add(index);
}
private void initialSprites() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++)
createSprite(i);
}
createSprites = false;
}
private void rndCreateSprite() {
Random rnd = new Random(System.currentTimeMillis());
int i = rnd.nextInt(4);
createSprite(i);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
for (int i = spriteList.size() - 1; i >= 0; i--) {
Sprite sprite = spriteList.get(i);
if (sprite.isTouched(event.getX(), event.getY())) {
if (currentColorNum == spriteListNum.get(i)) {
score++;
}else{
lives--;
if(lives==0){
theGameActivity.onGameOver();
}
}
if(score==3)
lives++;
rndCreateSprite();
removeSprite(i);
changeColor();
break;
}
}
}
}
return true;
}
private void removeSprite(int index) {
spriteList.remove(index);
spriteListNum.remove(index);
}
public void setColors() {
Paint paintRed = new Paint();
paintRed.setARGB(255, 236, 27, 36);
this.paintRed = paintRed;
Paint paintBlue = new Paint();
paintBlue.setARGB(255, 36, 72, 204);
this.paintBlue = paintBlue;
Paint paintGreen = new Paint();
paintGreen.setARGB(255, 34, 177, 76);
this.paintGreen = paintGreen;
Paint paintYellow = new Paint();
paintYellow.setARGB(255, 255, 242, 0);
this.paintYellow = paintYellow;
}
public void drawLines(Paint lineColor, Canvas canvas) {
int lineWidth = (int) (10*density);
int screenHeight = getHeight();
int screenWidth = getWidth();
canvas.drawRect(0, 0, lineWidth, getHeight(), lineColor);
canvas.drawRect(0, getHeight() - lineWidth, screenWidth, screenHeight,
lineColor);
canvas.drawRect(screenWidth - lineWidth, 0, screenWidth, screenHeight,
lineColor);
currentColor = lineColor;
}
public void changeColor() {
Random rnd = new Random();
int index = rnd.nextInt(spriteListNum.size());
this.currentColorNum = spriteListNum.get(index);
switch (index) {
case 0:
currentColor = paintBlue;
break;
case 1:
currentColor = paintRed;
break;
case 2:
currentColor = paintGreen;
break;
case 3:
currentColor = paintYellow;
break;
}
}
public float getDensity() {
density = getResources().getDisplayMetrics().density;
return density;
}
private void drawLives(Canvas canvas, Paint paint){
int xHeart= (int) (15*density);
int yHeart= (int) (12*density);
if (lives == 3) {
canvas.drawBitmap(livesPicture, xHeart,
yHeart, paint);
canvas.drawBitmap(livesPicture,
xHeart + livesPicture.getWidth() + 3*density,
yHeart, paint);
canvas.drawBitmap(livesPicture, xHeart + 2
* livesPicture.getWidth() + 6*density, yHeart, paint);
}
if (lives == 2) {
canvas.drawBitmap(livesPicture, xHeart,
yHeart, paint);
canvas.drawBitmap(livesPicture,
xHeart + livesPicture.getWidth() + 3,
yHeart, paint);
}
if (lives == 1) {
canvas.drawBitmap(livesPicture, xHeart,
yHeart, paint);
}
if (lives > 3) {
livesString = String.valueOf(lives);
final String lives = livesString + "x";
canvas.drawText(lives, 35 * getDensity(), 30 * getDensity(), paint);
canvas.drawBitmap(livesPicture, 15 * getDensity() + 2
* livesPicture.getWidth() + 6, 12 * getDensity(), paint);
}
}
public int getScore() {
return this.score;
}
}
I am a beginner so I really would appreciate some help.
Edit:
Don't create new variables inside the onDraw statement.
So the variables like yTextPos (int) or fontSize(int) from the draw-method should be created above with all the other global variables? Isn't this make it more confusing? Or what are the benefits?
Also, what is line 79 in GameView.java?
Do you mean
canvas.drawColor(Color.DKGRAY);
? This gives the background of the game the color DKGRAY. I don't have a specific image for the background yet.
I believe you should set your game running loop to false when you are in the game over state. You might need to join or something as well.
theGameLoopThread.setRunning(true);
theGameActivity.onGameOver();

Drag ImageView Or Bitmap Upon Touch

I currently have something working where I can drag a box horizontally on the screen (what I want it to do). However, it works when you click ANYWHERE on the screen, and I want it to work only when the box has been clicked. I have tried implementing this in different ways, and I've looked all over the place and still remain lost. Can anybody help? I also can't figure out how a bitmap is placed (I'm using a bitmap right now as I can't for the life of me figure out how to implement the ImageView inside my SurfaceView). If I say my bitmap is placed at 0,0 will that place the bitmap according to its top left corner at 0,0? I also had an algorithm for stopping the box when it reached an edge, but I'll just have to rewrite that as I must have deleted it. Please if you can offer your knowledge I would GREATLY appreciate it
public class BoardView extends SurfaceView implements SurfaceHolder.Callback{
Context mContext;
private BoardThread thread;
private float box_x = 140;
private float box_y = 378;
ImageView i = (ImageView) findViewById(R.id.box_view);
Bitmap box =
(BitmapFactory.decodeResource
(getResources(), R.drawable.box));
private float boxWidth = box.getWidth();
private float boxHeight = box.getHeight();
public BoardView(Context context){
super(context);
//surfaceHolder provides canvas that we draw on
getHolder().addCallback(this);
// controls drawings
thread = new BoardThread(getHolder(),this);
//intercepts touch events
setFocusable(true);
}
#Override
public void onDraw(Canvas canvas){
canvas.drawColor(Color.WHITE);
//draw box and set start location
canvas.drawBitmap(box, box_x - (boxWidth/2),
box_y - (boxHeight/2), null);
}
#Override
public boolean onTouchEvent(MotionEvent event){
//boolean mode = false;
if(event.getAction() == MotionEvent.ACTION_DOWN){
//int x = (int)event.getX();
//int y = (int)event.getY();
//if (x > box_x && x < box_x + 29 && y > box_y && y < box_y + 30){
//mode = true;
box_x = (int)event.getX();
//}
}
if(event.getAction() == MotionEvent.ACTION_MOVE) {
//int x = (int)event.getX();
//int y = (int)event.getY();
//if (mode == true){
box_x = (int)event.getX();
//}
}
invalidate();
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height ){
}
#Override
public void surfaceCreated(SurfaceHolder holder){
thread.startRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
thread.startRunning(false);
thread.stop();
}
}
Simply check the touch event x and y coordinate, and check if this x,y-combination is within the box's bounds. I can see you are on the right path by looking at your commented out code.
Do something like this:
RectF rect = new RectF(x,y, x + box.getWidth(), y+box.geHeight());
if(rect.contains(touchX, touchY)) {
// You hit the box, allow dragging...
}
Try this:
package teste.com.br.teste;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tacila on 03/07
*/
public class Game extends View {
private Context context;
private BitmaptArrastavel bmArrastavel;
private BitmaptArrastavel bmArrastavel2;
private BitmaptArrastavel bmArrastavelTeste;
private List<BitmaptArrastavel> btms;
private BitmaptArrastavel[] btmsAtivas;
private BitmaptArrastavel[] lake;
private BitmaptArrastavel[] ativos;
private int qntDeItens = 5;
public Game(Context context) {
super(context);
this.context = context;
init();
}
public void init() {
btms = new ArrayList<BitmaptArrastavel>();
btmsAtivas = new BitmaptArrastavel[1];
ativos=new BitmaptArrastavel[1];
lake = new BitmaptArrastavel[3];
lake[0] = new BitmaptArrastavel(escalaBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.cartadc)), 200);
lake[1] = new BitmaptArrastavel(escalaBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.cartaao)), 210);
lake[2] = new BitmaptArrastavel(escalaBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.cartake)), 220);
btms.add(bmArrastavel);
btms.add(bmArrastavelTeste);
btms.add(bmArrastavel2);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRGB(0,0,139);
for(int i = 0; i<=2; i++){
lake[i].drawOnCanvas(canvas);
}
}
public void travarArr(float x, float y ){
for(int i = 0; i<=2 ; i++){
if(lake[i].isDentro(x,y)){
ativos[0]=lake[i];
}
}
}
public void destravarBitmap() {
ativos[0]=null;
}
public Bitmap escalaBitmap(Bitmap bm) {
return Bitmap.createScaledBitmap(bm, 200, 300, false);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
System.out.println("Dentro do MotionEvent.ActionDown");
travarArr(event.getX(),event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
System.out.println("Dentro do MotionEvent.ActionUP e ActionCancel tenho q entrar no destrava ");
destravarBitmap();
break;
case MotionEvent.ACTION_MOVE:
System.out.println("Dentro do MotionEvent.ActionMove");
for(int i = 0; i<ativos.length;i++){
if(ativos[i]!=null){
ativos[i].mover((int)event.getX(),(int)event.getY());
invalidate();
}
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
System.out.println("Dentro do MotionEvent.ActionPointerDown");
travarArr(event.getX(), event.getY());
break;
case MotionEvent.ACTION_POINTER_UP:
System.out.println("Dentro do MotionEvent.ActionPointerUp");
destravarBitmap();
break;
default:
return super.onTouchEvent(event);
}
return true;
}
// int rotation = 0;
//
// public Bitmap vertical() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap bm = escalaBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.carta4c));
// return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
// }
}
The class BitmapArrastavel
package teste.com.br.teste;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* Created by Tacila on 05/07/2017.
*/
public class BitmaptArrastavel {
public int x, y, altura, largura;
private Bitmap bitmap;
public BitmaptArrastavel(Bitmap b, int x) {
bitmap = b;
this.x = x;
init();
}
public void init() {
largura = 200;
altura = 350;
}
public Bitmap escalaBitmap(Bitmap bm) {
return Bitmap.createScaledBitmap(bm, largura, altura, false);
}
public boolean isDentro(float x, float y) {
return (x >= this.x && x <= this.x + largura && y >= this.y && y <= this.y + altura);
}
public void drawOnCanvas(Canvas canvas) {
canvas.drawBitmap(bitmap, x, y, null);
}
public void mover(int x, int y) {
this.x = x;
this.y = y;
}
}

Rainbow type color picker in Android

I am New to Android. My Requirement is to implement a color picker which scrolls the colors in rainbow model from that I want to pick a color.
for the color picker use the ColorPickerDialog class from API Demos, And how to use it's describe in this code. So it's try.
package com.SampleCanvas;
import java.util.ArrayList;
import com.SampleCanvas.ColorPickerDialog.OnColorChangedListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
public class SampleCanvasActivity extends Activity implements OnTouchListener, OnClickListener, OnColorChangedListener {
DrawPanel dp;
private ArrayList<Path> pointsToDraw = new ArrayList<Path>();
private Paint mPaint;
Path path;
int color;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dp = new DrawPanel(this);
setContentView(R.layout.main);
dp = new DrawPanel(this);
dp.setOnTouchListener(this);
Button btn=(Button)findViewById(R.id.btnColor);
btn.setOnClickListener(this);
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(5);
FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout);
fl.addView(dp,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
dp.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dp.resume();
}
public boolean onTouch(View v, MotionEvent me) {
// TODO Auto-generated method stub
synchronized(pointsToDraw)
{
if(me.getAction() == MotionEvent.ACTION_DOWN){
path = new Path();
path.moveTo(me.getX(), me.getY());
//path.lineTo(me.getX(), me.getY());
pointsToDraw.add(path);
}else if(me.getAction() == MotionEvent.ACTION_MOVE){
path.lineTo(me.getX(), me.getY());
}else if(me.getAction() == MotionEvent.ACTION_UP){
//path.lineTo(me.getX(), me.getY());
}
}
return true;
}
public class DrawPanel extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false ;
public DrawPanel(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk == true){
if(!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 0, 0, 0);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
synchronized(pointsToDraw)
{
for (Path path : pointsToDraw) {
canvas.drawPath(path, mPaint);
}
}
}
public void pause(){
isItOk = false;
while(true){
try{
t.join();
}catch(InterruptedException e){
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOk = true;
t = new Thread(this);
t.start();
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnColor:
new ColorPickerDialog(this, this,mPaint.getColor()).show();
break;
default:
break;
}
}
public void colorChanged(int color) {
// TODO Auto-generated method stub
mPaint.setColor(color);
}
}
And The Color Picker Class is
package com.SampleCanvas;
import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.graphics.*;
import android.view.MotionEvent;
import android.view.View;
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private OnColorChangedListener mListener;
private int mInitialColor;
private static class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
#Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0,
CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int floatToByte(float x) {
int n = java.lang.Math.round(x);
return n;
}
private int pinToByte(int n) {
if (n < 0) {
n = 0;
} else if (n > 255) {
n = 255;
}
return n;
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int)p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i+1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int rotateColor(int color, float rad) {
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir),
pinToByte(ig), pinToByte(ib));
}
private static final float PI = 3.1415926f;
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float)java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context,
OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
setContentView(new ColorPickerView(getContext(), l, mInitialColor));
setTitle("Pick a Color");
}
}

Categories

Resources