public class MovingBagView extends View {
private Bitmap bag[] = new Bitmap[2];
private int bagX;
private int bagY = 1000;
private int bagSpeed;
private Boolean touch = false;
private int canvasWidth, canvasHeight;
private int yellowX = 500, yellowY, yellowSpeed = -16;
private Paint yellowPaint = new Paint();
private int score;
private Bitmap backgroundImage;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];
public MovingBagView(Context context) {
super(context);
bag[0] = BitmapFactory.decodeResource(getResources(), R.drawable.bag1);
bag[1] = BitmapFactory.decodeResource(getResources(), R.drawable.bag2);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
yellowPaint.setColor(Color.YELLOW);
yellowPaint.setAntiAlias(false);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(40);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.heart);
life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.heart_grey);
bagX = 10;
score = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvasWidth = canvas.getWidth();
canvasHeight = canvas.getHeight();
canvas.drawBitmap(backgroundImage, 0, 0, null);
int minBagX = bag[0].getWidth();
int maxBagX = canvasWidth - bag[0].getWidth() * 2;
bagX = bagX + bagSpeed;
if (bagX < minBagX) {
bagX = minBagX;
}
if (bagX >= maxBagX) {
bagX = maxBagX;
}
bagSpeed = bagSpeed + 2;
if (touch) {
canvas.drawBitmap(bag[1], bagX, bagY, null);
}
else {
canvas.drawBitmap(bag[0], bagX, bagY, null);
}
yellowY = yellowY - yellowSpeed;
if (hitBallChecker(yellowX, yellowY)) {
score = score + 10;
yellowY = -100;
}
if (yellowY < 0) {
yellowY = canvasHeight + 21;
yellowX = (int)Math.floor(Math.random() * (maxBagX - minBagX)) + maxBagX;
}
canvas.drawCircle(yellowX, yellowY, 15, yellowPaint);
canvas.drawText("Score : " + score, 20, 60, scorePaint);
canvas.drawBitmap(life[0], 500, 10, null);
canvas.drawBitmap(life[0], 570, 10, null);
canvas.drawBitmap(life[0], 640, 10, null);
}
public boolean hitBallChecker(int x, int y) {
if (bagY < y && y < (bagY + bag[0].getHeight()) && bagX < x && x < (bagX + bag[0].getWidth())) {
return true;
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touch = true;
bagSpeed = -22;
}
return true;
}
}
I've figured out how to make the balls drop from the top of the screen. The code is supposed to make multiple yellow balls drop from the top of the screen, but only one yellow ball drops. Random yellow balls are supposed to drop from the top, and they drop from different positions. You can see the preview of it below:
To implement this, you should consider creating a custom object Ball
public class Ball{
public int x;
public int y;
public int speed;
public Ball(int x, int y, int speed){
this.x = x;
this.y = y;
this.speed = speed;
}
}
Then you can add multiple Balls in an ArrayList and in the draw() you iterate through every Ball in the array and do what you've been doing to one Ball with each.
for(int i = 0; i < balls.length(); i++){
Ball ball = balls.get(i);
ball.y -= ball.speed;
// check for collisions
// draw ball
}
Related
Bro How To Add Hit Sound Touch Sound Give ME Full Code.I Do't Undestand
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SoundPlayer sound;
MediaPlayer player;
List item
private GameView gameView;
private final Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.bg_music);
mediaPlayer.setLooping(true);
mediaPlayer.start();
gameView = new GameView(this);
setContentView(gameView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(() -> gameView.invalidate());
}
},0,Interval);
}
#Override
protected void onResume() {
super.onResume();
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
}
My Game View Class Code
List item
public class GameView extends View {
private SoundPlayer soundPlayer;
MediaPlayer player;
private final Bitmap[] mouse = new Bitmap[2];
private Bitmap orange;
private Bitmap malone;
private Bitmap grapes;
private Bitmap cat;
private Bitmap cat2;
private final int mouseX = 50;
private int mouseY;
private int mouseSpeed;
private int orangeX;``
private int orangeY;
private int maloneX;
private int maloneY;
private int grapesX;
private int grapesY;
private int catX;
private int catY;
private int cat2X;
private int cat2Y;
private int score,lifeCounterOfCat;
private final Paint scorePaint = new Paint();
private boolean touch = false;
private Bitmap backgroundImage;
private final Bitmap[] life = new Bitmap[2];
public GameView(Context context) {
super(context);
mouse[0] = BitmapFactory.decodeResource(getResources(), R.drawable.mouse);
mouse[0] = Bitmap.createScaledBitmap(mouse[0], 200, 200, true);
mouse[1] = BitmapFactory.decodeResource(getResources(), R.drawable.mouse2);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
backgroundImage = Bitmap.createScaledBitmap(backgroundImage, (int) (backgroundImage.getWidth() * 0.6), (int) (backgroundImage.getHeight() * 0.6), true);
scorePaint.setColor(Color.WHITE);
scorePaint.setTextSize(70);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
orange = BitmapFactory.decodeResource(getResources(), R.drawable.orange);
orange = Bitmap.createScaledBitmap(orange, 150, 150, true);
malone = BitmapFactory.decodeResource(getResources(), R.drawable.melone);
malone = Bitmap.createScaledBitmap(malone, 150, 150, true);
grapes = BitmapFactory.decodeResource(getResources(), R.drawable.grapes);
grapes = Bitmap.createScaledBitmap(grapes, 190, 190, true);
cat = BitmapFactory.decodeResource(getResources(), R.drawable.cat);
cat = Bitmap.createScaledBitmap(cat, 500, 400, true);
cat2 = BitmapFactory.decodeResource(getResources(), R.drawable.cat2);
cat2= Bitmap.createScaledBitmap(cat, 500, 400, true);
life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.life);
life[0] = Bitmap.createScaledBitmap(life[0], 140, 140, true);
life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.life_down);
life[1] = Bitmap.createScaledBitmap(life[1], 140, 140, true);
mouseY = 800;
score = 0;
lifeCounterOfCat = 4;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int canvasWidth = getWidth();
int canvasHeight = getHeight();
canvas.drawBitmap(backgroundImage,0,0,null);
int minMouseY = mouse[0].getHeight();
int maxMouseY= canvasHeight - mouse[0].getHeight();
mouseY = mouseY + mouseSpeed;
if (mouseY <minMouseY)
{
mouseY = minMouseY;
}
if (mouseY >maxMouseY)
{
mouseY =maxMouseY;
}
mouseSpeed = mouseSpeed + 3;
if (touch)
{
canvas.drawBitmap(mouse[1],mouseX,mouseY,null);
touch = false;
}
else
{
canvas.drawBitmap(mouse[0],mouseX,mouseY,null);
}
int orangeSpeed = 3;
orangeX = orangeX - orangeSpeed;
if (hitBallChecker(orangeX , orangeY))
{
score = score + 10;
orangeX = - 100;
}
orangeX = orangeX- orangeSpeed;
if (orangeX<0)
{
orangeX = canvasWidth + 21;
orangeY = (int) Math.floor(Math.random() * (maxMouseY - minMouseY)) + minMouseY;
}
int maloneSpeed = 6;
maloneX = maloneX - maloneSpeed;
if (hitBallChecker(maloneX , maloneY))
{
score = score + 25;
maloneX= -100;
}
maloneX = maloneX- maloneSpeed;
if (maloneX < 0)
{
maloneX = canvasWidth + 21;
maloneY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
int grapesSpeed = 5;
grapesX = grapesX - grapesSpeed;
if (hitBallChecker(grapesX , grapesY))
{
score = score + 35;
grapesX = -120;
}
grapesX = grapesX- grapesSpeed;
if (grapesX < 0)
{
grapesX = canvasWidth + 21;
grapesY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
int catSpeed = 8;
catX = catX - catSpeed;
hitBallChecker(catX, catY);
int cat2Speed = 5;
cat2X = cat2X - cat2Speed;
if (hitBallChecker(cat2X , cat2Y)) {
catX = -800;
lifeCounterOfCat--;
cat2X = -500;
lifeCounterOfCat--;
if (lifeCounterOfCat == 0)
{
Toast.makeText(getContext(), "Game Over", Toast.LENGTH_SHORT).show();
Intent gameOverIntent = new Intent(getContext(), GameOver.class);
gameOverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
getContext().startActivity(gameOverIntent);
}
}
catX = catX- catSpeed;
if (catX < 0)
{
catX = canvasWidth + 500;
catY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
cat2X = cat2X- cat2Speed;
if (cat2X < 0)
{
cat2X = canvasWidth + 400;
cat2Y = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
canvas.drawText("score :" + score, 20,60, scorePaint);
//Life Counter//
for (int i=0; i<3; i++)
{
int x = (int) (700 + life[0]. getWidth() * 0.8* i);
int y = 30;
if (i < lifeCounterOfCat)
{
canvas.drawBitmap(life[0],x,y,null);
}
else
{
canvas.drawBitmap(life[1],x,y,null);
}
}
canvas.drawBitmap(orange,orangeX,orangeY,null);
canvas.drawBitmap(malone, maloneX,maloneY,null);
canvas.drawBitmap(grapes,grapesX,grapesY,null);
canvas.drawBitmap(cat,catX,catY,null);
canvas.drawBitmap(cat2,cat2X,cat2Y,null);
}
public boolean hitBallChecker(int x, int y)
{
return mouseX < x && x < (mouseX + mouse[0].getWidth()) && mouseY < y && y < (mouseY + mouse[0].getHeight());
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event)
{
event.getAction();
{
touch = false;
mouseSpeed = - 22;
}
return true;
}
}
My project is about to censor the picture. It works like this: user choose a photo from gallery and when select an area of photo , this area change to the other color.
It works fine and my problem is that I couldn't save it my gallery.Saving picture to gallery is easy and I do it many time without error. But now I got no error and may method doesn't work.
here is my code:
public boolean save() {
if (mTouchRects.isEmpty() || bmMosaicLayer == null) {
return false;
}
Bitmap bitmap = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bmBaseLayer, 0, 0, null);
canvas.drawBitmap(bmMosaicLayer, 0, 0, null);
canvas.save();
try {
FileOutputStream fos = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "failed to write image content");
return false;
}
return true;
}
and in my activity :
else if (view.equals(btSave)) {
boolean succced = mvImage.save();
String text = "save image "
+ (succced ? " succeed" : " failed");
Toast.makeText(view.getContext(), text, Toast.LENGTH_SHORT)
.show();
}
here is my full code:
public class MosaicView extends ViewGroup {
public static final String TAG = "MosaicView";
public static enum Effect {
GRID, COLOR, BLUR,
};
public static enum Mode {
GRID, PATH,
}
// default image inner padding, in dip pixels
private static final int INNER_PADDING = 6;
// default grid width, in dip pixels
private static final int GRID_WIDTH = 5;
// default grid width, in dip pixels
private static final int PATH_WIDTH = 20;
// default stroke rectangle color
private static final int STROKE_COLOR = 0xff2a5caa;
// default stroke width, in pixels
private static final int STROKE_WIDTH = 6;
private int mImageWidth;
private int mImageHeight;
private Bitmap bmBaseLayer;
private Bitmap bmCoverLayer;
private Bitmap bmMosaicLayer;
private Point startPoint;
private int mGridWidth;
private int mPathWidth;
private int mStrokeWidth;
private int mStrokeColor;
private String inPath;
private String outPath;
private Effect mEffect;
private Mode mMode;
private Rect mImageRect;
private Paint mPaint;
private Rect mTouchRect;
private List<Rect> mTouchRects;
private Path mTouchPath;
private List<Rect> mEraseRects;
private int mMosaicColor;
private int mPadding;
private List<Path> mTouchPaths;
private List<Path> mErasePaths;
private boolean mMosaic;
public MosaicView(Context context) {
super(context);
initImage();
}
public MosaicView(Context context, AttributeSet attrs) {
super(context, attrs);
initImage();
}
private void initImage() {
mMosaic = true;
mTouchRects = new ArrayList<Rect>();
mEraseRects = new ArrayList<Rect>();
mTouchPaths = new ArrayList<Path>();
mErasePaths = new ArrayList<Path>();
mStrokeWidth = STROKE_WIDTH;
mStrokeColor = STROKE_COLOR;
mPadding = dp2px(INNER_PADDING);
mPathWidth = dp2px(PATH_WIDTH);
mGridWidth = dp2px(GRID_WIDTH);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setColor(mStrokeColor);
mImageRect = new Rect();
setWillNotDraw(false);
mMode = Mode.PATH;
mEffect = Effect.GRID;
}
public void setSrcPath(String absPath) {
File file = new File(absPath);
if (file == null || !file.exists()) {
Log.w(TAG, "invalid file path " + absPath);
return;
}
reset();
inPath = absPath;
String fileName = file.getName();
String parent = file.getParent();
int index = fileName.lastIndexOf(".");
String stem = fileName.substring(0, index);
String newStem = stem + "_mosaic";
fileName = fileName.replace(stem, newStem);
outPath = parent + "/" + fileName;
Size size = BitmapUtil.getImageSize(inPath);
mImageWidth = size.width;
mImageHeight = size.height;
bmBaseLayer = BitmapUtil.getImage(absPath);
bmCoverLayer = getCoverLayer();
bmMosaicLayer = null;
requestLayout();
invalidate();
}
public void setEffect(Effect effect) {
if (mEffect == effect) {
Log.d(TAG, "duplicated effect " + effect);
return;
}
this.mEffect = effect;
if (bmCoverLayer != null) {
bmCoverLayer.recycle();
}
bmCoverLayer = getCoverLayer();
if (mMode == Mode.GRID) {
updateGridMosaic();
} else if (mMode == Mode.PATH) {
updatePathMosaic();
}
invalidate();
}
public void setMode(Mode mode) {
if (mMode == mode) {
Log.d(TAG, "duplicated mode " + mode);
return;
}
if (bmMosaicLayer != null) {
bmMosaicLayer.recycle();
bmMosaicLayer = null;
}
this.mMode = mode;
invalidate();
}
private Bitmap getCoverLayer() {
Bitmap bitmap = null;
if (mEffect == Effect.GRID) {
bitmap = getGridMosaic();
} else if (mEffect == Effect.COLOR) {
bitmap = getColorMosaic();
} else if (mEffect == Effect.BLUR) {
bitmap = getBlurMosaic();
}
return bitmap;
}
private Bitmap getColorMosaic() {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Rect rect = new Rect(0, 0, mImageWidth, mImageHeight);
Paint paint = new Paint();
paint.setColor(mMosaicColor);
canvas.drawRect(rect, paint);
canvas.save();
return bitmap;
}
private Bitmap getBlurMosaic() {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return null;
}
if (bmBaseLayer == null) {
return null;
}
Bitmap bitmap = BitmapUtil.blur(bmBaseLayer);
return bitmap;
}
private Bitmap getGridMosaic() {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
int horCount = (int) Math.ceil(mImageWidth / (float) mGridWidth);
int verCount = (int) Math.ceil(mImageHeight / (float) mGridWidth);
Paint paint = new Paint();
paint.setAntiAlias(true);
for (int horIndex = 0; horIndex < horCount; ++horIndex) {
for (int verIndex = 0; verIndex < verCount; ++verIndex) {
int l = mGridWidth * horIndex;
int t = mGridWidth * verIndex;
int r = l + mGridWidth;
if (r > mImageWidth) {
r = mImageWidth;
}
int b = t + mGridWidth;
if (b > mImageHeight) {
b = mImageHeight;
}
int color = bmBaseLayer.getPixel(l, t);
Rect rect = new Rect(l, t, r, b);
paint.setColor(color);
canvas.drawRect(rect, paint);
}
}
canvas.save();
return bitmap;
}
public boolean isSaved() {
return (bmCoverLayer == null);
}
public void setOutPath(String absPath) {
this.outPath = absPath;
}
public void setGridWidth(int width) {
this.mGridWidth = dp2px(width);
}
public void setPathWidth(int width) {
this.mPathWidth = dp2px(width);
}
public int getGridWidth() {
return this.mGridWidth;
}
public void setStrokeColor(int color) {
this.mStrokeColor = color;
mPaint.setColor(mStrokeColor);
}
public void setMosaicColor(int color) {
this.mMosaicColor = color;
}
public int getStrokeColor() {
return this.mStrokeColor;
}
public void setStrokeWidth(int width) {
this.mStrokeWidth = width;
mPaint.setStrokeWidth(mStrokeWidth);
}
public int getStrokeWidth() {
return this.mStrokeWidth;
}
public void setErase(boolean erase) {
this.mMosaic = !erase;
}
public void clear() {
mTouchRects.clear();
mEraseRects.clear();
mTouchPaths.clear();
mErasePaths.clear();
if (bmMosaicLayer != null) {
bmMosaicLayer.recycle();
bmMosaicLayer = null;
}
invalidate();
}
public boolean reset() {
if (bmCoverLayer != null) {
bmCoverLayer.recycle();
bmCoverLayer = null;
}
if (bmBaseLayer != null) {
bmBaseLayer.recycle();
bmBaseLayer = null;
}
if (bmMosaicLayer != null) {
bmMosaicLayer.recycle();
bmMosaicLayer = null;
}
mTouchRects.clear();
mEraseRects.clear();
mTouchPaths.clear();
mErasePaths.clear();
return true;
}
public boolean save() {
if (mTouchRects.isEmpty() || bmMosaicLayer == null) {
return false;
}
Bitmap bitmap = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bmBaseLayer, 0, 0, null);
canvas.drawBitmap(bmMosaicLayer, 0, 0, null);
canvas.save();
try {
FileOutputStream fos = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "failed to write image content");
return false;
}
return true;
}
public boolean dispatchTouchEvent(MotionEvent event) {
super.dispatchTouchEvent(event);
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
Log.d(TAG, "action " + action + " x " + x + " y " + y);
if (mMode == Mode.GRID) {
onGridEvent(action, x, y);
} else if (mMode == Mode.PATH) {
onPathEvent(action, x, y);
}
return true;
}
private void onGridEvent(int action, int x, int y) {
if (x >= mImageRect.left && x <= mImageRect.right
&& y >= mImageRect.top && y <= mImageRect.bottom) {
int left = x;
int right = x;
int top = y;
int bottom = y;
if (startPoint == null) {
startPoint = new Point();
startPoint.set(x, y);
mTouchRect = new Rect();
} else {
left = startPoint.x < x ? startPoint.x : x;
top = startPoint.y < y ? startPoint.y : y;
right = x > startPoint.x ? x : startPoint.x;
bottom = y > startPoint.y ? y : startPoint.y;
}
mTouchRect.set(left, top, right, bottom);
}
if (action == MotionEvent.ACTION_UP) {
if (mMosaic) {
mTouchRects.add(mTouchRect);
} else {
mEraseRects.add(mTouchRect);
}
mTouchRect = null;
startPoint = null;
updateGridMosaic();
}
invalidate();
}
private void onPathEvent(int action, int x, int y) {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return;
}
if (x < mImageRect.left || x > mImageRect.right || y < mImageRect.top
|| y > mImageRect.bottom) {
return;
}
float ratio = (mImageRect.right - mImageRect.left)
/ (float) mImageWidth;
x = (int) ((x - mImageRect.left) / ratio);
y = (int) ((y - mImageRect.top) / ratio);
if (action == MotionEvent.ACTION_DOWN) {
mTouchPath = new Path();
mTouchPath.moveTo(x, y);
if (mMosaic) {
mTouchPaths.add(mTouchPath);
} else {
mErasePaths.add(mTouchPath);
}
} else if (action == MotionEvent.ACTION_MOVE) {
mTouchPath.lineTo(x, y);
updatePathMosaic();
invalidate();
}
}
private void updatePathMosaic() {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return;
}
long time = System.currentTimeMillis();
if (bmMosaicLayer != null) {
bmMosaicLayer.recycle();
}
bmMosaicLayer = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Bitmap bmTouchLayer = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setPathEffect(new CornerPathEffect(10));
paint.setStrokeWidth(mPathWidth);
paint.setColor(Color.BLUE);
Canvas canvas = new Canvas(bmTouchLayer);
for (Path path : mTouchPaths) {
canvas.drawPath(path, paint);
}
paint.setColor(Color.TRANSPARENT);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
for (Path path : mErasePaths) {
canvas.drawPath(path, paint);
}
canvas.setBitmap(bmMosaicLayer);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawBitmap(bmCoverLayer, 0, 0, null);
paint.reset();
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(bmTouchLayer, 0, 0, paint);
paint.setXfermode(null);
canvas.save();
bmTouchLayer.recycle();
Log.d(TAG, "updatePathMosaic " + (System.currentTimeMillis() - time));
}
private void updateGridMosaic() {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return;
}
long time = System.currentTimeMillis();
if (bmMosaicLayer != null) {
bmMosaicLayer.recycle();
}
bmMosaicLayer = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
float ratio = (mImageRect.right - mImageRect.left)
/ (float) mImageWidth;
Bitmap bmTouchLayer = Bitmap.createBitmap(mImageWidth, mImageHeight,
Config.ARGB_8888);
Canvas canvas = null;
canvas = new Canvas(bmTouchLayer);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(mStrokeColor);
for (Rect rect : mTouchRects) {
int left = (int) ((rect.left - mImageRect.left) / ratio);
int right = (int) ((rect.right - mImageRect.left) / ratio);
int top = (int) ((rect.top - mImageRect.top) / ratio);
int bottom = (int) ((rect.bottom - mImageRect.top) / ratio);
canvas.drawRect(left, top, right, bottom, paint);
}
paint.setColor(Color.TRANSPARENT);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
for (Rect rect : mEraseRects) {
int left = (int) ((rect.left - mImageRect.left) / ratio);
int right = (int) ((rect.right - mImageRect.left) / ratio);
int top = (int) ((rect.top - mImageRect.top) / ratio);
int bottom = (int) ((rect.bottom - mImageRect.top) / ratio);
canvas.drawRect(left, top, right, bottom, paint);
}
canvas.setBitmap(bmMosaicLayer);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawBitmap(bmCoverLayer, 0, 0, null);
paint.reset();
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(bmTouchLayer, 0, 0, paint);
paint.setXfermode(null);
canvas.save();
bmTouchLayer.recycle();
Log.d(TAG, "updateGridMosaic " + (System.currentTimeMillis() - time));
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw canvas " + canvas + " mTouchRect " + mTouchRect);
if (bmBaseLayer != null) {
canvas.drawBitmap(bmBaseLayer, null, mImageRect, null);
}
if (bmMosaicLayer != null) {
canvas.drawBitmap(bmMosaicLayer, null, mImageRect, null);
}
if (mTouchRect != null) {
canvas.drawRect(mTouchRect, mPaint);
}
}
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
if (mImageWidth <= 0 || mImageHeight <= 0) {
return;
}
int contentWidth = right - left;
int contentHeight = bottom - top;
int viewWidth = contentWidth - mPadding * 2;
int viewHeight = contentHeight - mPadding * 2;
float widthRatio = viewWidth / ((float) mImageWidth);
float heightRatio = viewHeight / ((float) mImageHeight);
float ratio = widthRatio < heightRatio ? widthRatio : heightRatio;
int realWidth = (int) (mImageWidth * ratio);
int realHeight = (int) (mImageHeight * ratio);
int imageLeft = (contentWidth - realWidth) / 2;
int imageTop = (contentHeight - realHeight) / 2;
int imageRight = imageLeft + realWidth;
int imageBottom = imageTop + realHeight;
mImageRect.set(imageLeft, imageTop, imageRight, imageBottom);
}
private int dp2px(int dip) {
Context context = this.getContext();
Resources resources = context.getResources();
int px = Math
.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dip, resources.getDisplayMetrics()));
return px;
}
}
and here:
inPath = absPath;
String fileName = file.getName();
String parent = file.getParent();
int index = fileName.lastIndexOf(".");
String stem = fileName.substring(0, index);
String newStem = stem + "_mosaic";
fileName = fileName.replace(stem, newStem);
outPath = parent + "/" + fileName;
here is related to what you find.
here is the class which extends surface view , in its run method i've called the method to animate ball but the ball isnt animating
public class OurView extends SurfaceView implements Runnable
{
Canvas c;
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
Rect racketTop,racketBottom;
int TopLeft ;
int TopRight ;
int TopTop ;
int TopBottom;
int bottomLeft;
int bottomRight;
int bottomTop;
int bottomBottom;
GameState state;
public OurView(Context context) {
super(context);
holder = getHolder();
state = new GameState();
}
#Override
public void run() {
while (isItOk == true) {
if (!holder.getSurface().isValid())
continue;
c = holder.lockCanvas();
c.drawARGB(0, 0, 0, 0);
TopLeft = ((c.getWidth() / 2) / 2) + 50;
TopRight = (c.getWidth() / 2) + ((c.getWidth() / 2) / 2) - 50;
TopTop = getTop();
TopBottom = 10;
bottomLeft = ((c.getWidth() / 2) / 2) + 50;
bottomRight = (c.getWidth() / 2) + ((c.getWidth() / 2) / 2) - 50;
bottomTop = getBottom() - 10;
bottomBottom = getBottom();
racketTop = new Rect(); // for top racket
racketTop.set(TopLeft, TopTop, TopRight, TopBottom); //left = ((c.getWidth()/2)/2)+50
//top = getTop()
//right = (c.getWidth()/2)+((c.getWidth()/2)/2)-50
//bottom = 10
racketBottom = new Rect(); // FOR BOTTOM RACKET
racketBottom.set(bottomLeft, bottomTop, bottomRight, bottomBottom); //left = ((c.getWidth()/2)/2)+50
// top = getBottom()-10
// right = (c.getWidth()/2)+((c.getWidth()/2)/2)-50
// bottom = getBottom()
Paint white = new Paint();
white.setColor(Color.WHITE);
white.setStyle(Paint.Style.FILL);
c.drawRect(racketTop, white);
c.drawRect(racketBottom, white);
here i called the method
state.update();
state.draw(c,white);
holder.unlockCanvasAndPost(c);
}
}
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();
}
here is the class where ball is defined
public class GameState {
int ballx,bally; //ball x and y position
int ball_size = 20; // size of ball
static int ballvelx = 3; // velocity x of ball
static int ballvely = 3; // velocity y of ball
public GameState() {
}
public void update()
{
ballx += ballvelx;
bally += ballvely;
}
public void draw(Canvas canvas, Paint paint)
{
//objects color
paint.setColor(Color.WHITE);
ballx = canvas.getWidth()/2;
bally = canvas.getHeight()/2;
//ball
canvas.drawCircle(ballx,bally,ball_size,paint);
}
}
help me this is my first android game
Without judging on the rest of your code:
ballx = canvas.getWidth()/2;
bally = canvas.getHeight()/2;
This resets the position of your ball every time you draw it.
No wonder it does not move, when you reset its position.
Call update() instead, so the ball is moved.
I am trying to write an android application that draws Circles at random positions over and over forever. This is already done in my code. The next objective for me is to slowly animate these circles to make them "grow" onto the screen. Basically increment the radius of the circle from 0 to 300 very fast I did this by creating a for loop like this.
for(int i = 0;i< 300; i++){
canvas.drawCircle(randomWidthOne, randomHeightOne,i, newPaint);
}
unfortunately this does not perform the desired result. Instead it just displays the circles at the end radius of 300. Here is my code for the class that draws the circles. Please let me know if there is anything in the class that is interfering with what I am trying to accomplish.
public class SplashLaunch extends View{
Handler cool = new Handler();
DrawingView v;
Paint newPaint = new Paint();
int randomWidthOne = 0;
int randomHeightOne = 0;
private float radiusNsix = 10;
private float radiusNfive = 25;
private float radiusNfour = 50;
private float radiusNthree = 100;
private float radiusNtwo = 150;
private float radiusNone = 200;
private float radiusZero = 250;
private float radiusOne = 300;
final int redColorOne = Color.RED;
final int greenColorOne = Color.GREEN;
private static int lastColorOne;
double startTime = System.currentTimeMillis();
ObjectAnimator radiusAnimator;
private final Random theRandom = new Random();
public SplashLaunch(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
private final Runnable circleUpdater = new Runnable() {
#Override
public void run() {
lastColorOne = theRandom.nextInt(2) == 1 ? redColorOne : greenColorOne;
newPaint.setColor(lastColorOne);
cool.postDelayed(this, 1000);
invalidate();
}
};
#Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
cool.post(circleUpdater);
}
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
cool.removeCallbacks(circleUpdater);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
if(theRandom == null){
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}else {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}
for(int i = 0;i< 300; i++){
canvas.drawCircle(randomWidthOne, randomHeightOne,i, newPaint);
}
}
public void setRadiusOne(float value){
this.radiusOne = value;
invalidate();
}
public int startAnimation(int animationDuration) {
if (radiusAnimator == null || !radiusAnimator.isRunning()) {
// Define what value the radius is supposed to have at specific time values
Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
Keyframe kf2 = Keyframe.ofFloat(0.5f, 180f);
Keyframe kf1 = Keyframe.ofFloat(1f, 360f);
// If you pass in the radius, it will be calling setRadius method, so make sure you have it!!!!!
PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("radiusOne", kf0, kf1, kf2);
radiusAnimator = ObjectAnimator.ofPropertyValuesHolder(this, pvhRotation);
radiusAnimator.setInterpolator(new LinearInterpolator());
radiusAnimator.setDuration(animationDuration);
radiusAnimator.start();
}
else {
Log.d("Circle", "I am already running!");
}
return animationDuration;
}
public void stopAnimation() {
if (radiusAnimator != null) {
radiusAnimator.cancel();
radiusAnimator = null;
}
}
public boolean getAnimationRunning() {
return radiusAnimator != null && radiusAnimator.isRunning();
}
}
Call this.invalidate() to force redraw on next frame:
private int x = -1;
private int y = -1;
private int r = -1;
private int stepsLeft = 300;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (x < 0) { // generate new circle
int[] xy = generateXY();
x = xy[0];
y = xy[1];
r = 0;
}
if (stepsLeft > 0) {
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x, y, r, newPaint); // draw circle with new radius
r++; // increment radius
stepsLeft--; // decrement steps
this.invalidate(); // invalidate the view
}
}
private int[] generateXY() {
if (theRandom == null) {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
} else {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}
return new int[]{randomWidthOne, randomHeightOne};
}
Have a look at the property animator.
Block Class
public class Block {
public enum BlockType {
Dirt,
Grass,
Selection
}
BlockType Type;
Vector2f Position;
Image texture;
boolean breakable;
public Block(BlockType Type, Vector2f Position, Image texture, boolean breakable) {
this.Type = Type;
this.Position = Position;
this.texture = texture;
this.breakable = breakable;
}
public BlockType getType() {
return Type;
}
public void setType(BlockType value) {
Type = value;
}
public Vector2f getPosition() {
return Position;
}
public void setPosition(Vector2f value) {
Position = value;
}
public Image gettexture() {
return texture;
}
public void settexture(Image value) {
texture = value;
}
public boolean getbreakable() {
return breakable;
}
public void setbreakable(boolean value) {
breakable = value;
}
}
Tile Generation Class
public class TileGen {
Block block;
public Block[] tiles = new Block[3];
public int width, height;
public int[][] index;
boolean selected;
int mouseX, mouseY;
int tileX, tileY;
Image dirt, grass, selection;
SpriteSheet tileSheet;
public void init() throws SlickException {
tileSheet = new SpriteSheet("assets/tiles/tileSheet.png", 64, 64, new Color(0,0,0));
grass = tileSheet.getSprite(0,0);
dirt = tileSheet.getSprite(64,0);
selection = tileSheet.getSprite(128,0);
tiles[0] = new Block(BlockType.Grass, new Vector2f(tileX,tileY), grass, true);
tiles[1] = new Block(BlockType.Dirt, new Vector2f(tileX,tileY), dirt, true);
width = 50;
height = 50;
index = new int[width][height];
Random rand = new Random();
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
index[x][y] = rand.nextInt(2);
}
}
}
public void update(GameContainer gc) {
Input input = gc.getInput();
mouseX = input.getMouseX();
mouseY = input.getMouseY();
tileX = mouseX / width;
tileY = mouseY / height;
if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
selected = true;
}
else{
selected = false;
}
System.out.println(tileX);
}
public void render() {
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tiles[index[x][y]].texture.draw(x * 64, y *64);
if(IsMouseInsideTile(x, y))
selection.draw(x * 64, y * 64);
if(selected && tiles[index[x][y]].breakable) {
if(tiles[index[tileX][tileY]].texture == grass)
tiles[index[tileX][tileY]].texture = dirt;
}
}
}
}
public boolean IsMouseInsideTile(int x, int y)
{
return (mouseX >= x * 64 && mouseX <= (x + 1) * 64 &&
mouseY >= y * 64 && mouseY <= (y + 1) * 64);
}
I am not sure what I am doing wrong, I am new to slick2d. When I try to init my tiles from the spritesheet it throws an exception. The init in my tileGen class is where the problem is.
Exception in thread "main" java.lang.RuntimeException: SubImage out of sheet bounds: 64,0
at org.newdawn.slick.SpriteSheet.getSprite(SpriteSheet.java:208)
at com.synyst3r1.game.TileGen.init(TileGen.java:32)
at com.synyst3r1.game.Game.init(Game.java:23)
at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:390)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
at com.synyst3r1.game.Game.main(Game.java:50)
The (x, y) in getSprite() are the cell position, not the pixel position. So, you want getSprite(1, 0) and getSprite(2, 0) (assuming your image is 192x64).