Trying to Call an Activity from a Surface View (via onTouch) - android

I've been trying to call an activity from a surface view via On Touch. However, with the code I've constructed (and I've tried all possible trials and errors, I'm a novice programmer fyi), I keep clicking on the surface view and nothing happens.
I badly need some help guys, this is a school project :3
Thanks!
package com.projtimesequencesrc;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewer extends View implements OnTouchListener {
private Context svc;
float x, y;
Bitmap bgd, main;
Bitmap dialog;
Rect dialogsrc, dialogdst;
//dog
Bitmap dog;
Rect dogsrc, dogdst;
Paint p;
//Molly
Bitmap molly;
Rect mollysrc, mollydst;
//Molly2
Bitmap youngstar;
Rect youngstarsrc, youngstardst;
//Bear
Bitmap bear;
Rect bearsrc, beardst;
Thread tbear, tdbear;
Runnable rbear, dbear;
//man1
Bitmap man1;
Rect mansrc, mandst;
// Main Character
Rect bgdst, charsrc, chardst;
Thread tstory, tdstory;
Runnable rstory, dstory;
protected void onDraw (Canvas c) {
super.onDraw(c);
bgdst.right=getWidth();
bgdst.bottom=getHeight();
c.drawBitmap(bgd, null, bgdst, p);
c.drawBitmap(main, charsrc,chardst, p);
c.drawBitmap(dog, dogsrc, dogdst, p);
c.drawBitmap(bear, bearsrc, beardst, p);
c.drawBitmap(man1, mansrc, mandst, p);
c.drawBitmap(dialog, dialogsrc, dialogdst, p);
c.drawBitmap(molly, mollysrc,mollydst, p);
c.drawBitmap(youngstar, youngstarsrc, youngstardst, p);
invalidate();
}
void sqyoungstar2() {
int count = 0;
while (true) {
youngstarsrc.left += 64;
youngstarsrc.right += 64;
if (youngstarsrc.left > (64*6)) {
youngstarsrc.left = 0;
youngstarsrc.right = 64;
}
SystemClock.sleep(200);
count++;
if (count > 38) {
break;
}
}
}
void sqyoungstar1() {
youngstarsrc.left = 0;
youngstarsrc.right = 64;
youngstarsrc.top = 64*2;
youngstarsrc.bottom = 64*3;
youngstardst.left = 280;
youngstardst.right = 330;
youngstardst.top = 200;
youngstardst.bottom = 250;
sqyoungstar2();
}
void seq4() {
// Main Character
charsrc.left = 0;
charsrc.right = 64;
charsrc.top = (64*9);
charsrc.bottom = (64*10);
mansrc.left = 0;
mansrc.right = 64;
mansrc.top = (64*9);
mansrc.bottom = (64*10);
int count = 0;
while (true) {
charsrc.left += 64;
charsrc.right += 64;
if (charsrc.left > (64*8)) {
charsrc.left = 0;
charsrc.right = 64;
}
chardst.offset(-5, 0);
SystemClock.sleep(100);
count++;
if (count > 38) {
break;
}
}
SystemClock.sleep(1000);
}
void seq3() {
// Main Character
charsrc.left = 0;
charsrc.top = (64*11);
charsrc.right= 64;
charsrc.bottom = (64*12);
SystemClock.sleep(3000);
seq4();
}
void seq2() {
// Main Character
int count = 0;
while (true) {
charsrc.left += 64;
charsrc.right += 64;
if (charsrc.left > (64 * 6)) {
charsrc.left = 0;
charsrc.right = 64;
}
chardst.offset(5, 0);
SystemClock.sleep(100);
count++;
if (count > 38) {
break;
}
}
seq3();
}
void sequence1() {
// main character
dialogsrc.left = 0;
dialogsrc.right = 536;
dialogsrc.top = 0;
dialogsrc.bottom = 120;
dialogdst.left = 100;
dialogdst.right = 736;
dialogdst.top = 50;
dialogdst.bottom = 170;
charsrc.left = 0;
charsrc.top = (64*11);
charsrc.right= 64;
charsrc.bottom = (64*12);
chardst.left = 192;
chardst.top = 255;
chardst.right= 256;
chardst.bottom = 315;
mansrc.left = 0;
mansrc.right = 64;
mansrc.top = (64*3);
mansrc.bottom = (64*4);
mandst.left = 150;
mandst.right = 214;
mandst.top = 255;
mandst.bottom = 315;
SystemClock.sleep(2000);
seq2();
}
void sqdog4() {
dogsrc.left = 0;
dogsrc.right = 80;
dogsrc.top = 0;
dogsrc.bottom = 80;
SystemClock.sleep(2000);
}
void sqdog3() {
dogsrc.left = 80;
dogsrc.right = 80*2;
dogsrc.top = 80;
dogsrc.bottom = 80*2;
SystemClock.sleep(2000);
sqdog4();
}
void sqdog2() {
int count = 0;
while (true) {
dogsrc.left +=80;
dogsrc.right +=80;
if (dogsrc.left > (80*2)) {
dogsrc.left = 0;
dogsrc.right = 80;
}
SystemClock.sleep(100);
count++;
if (count > 28) {
break;
}
}
SystemClock.sleep(5000);
// insert sequence
sqdog3();
}
void sqdog1() {
dogsrc.left = 0;
dogsrc.right = 80;
dogsrc.top = 0;
dogsrc.bottom = 80;
dogdst.left = 470;
dogdst.right = 535;
dogdst.top = 280;
dogdst.bottom = 315;
sqdog2();
}
void sqbear2() {
int count = 0;
while (true) {
bearsrc.left+= 56;
bearsrc.right+=56;
if (bearsrc.left > 56) {
bearsrc.left = 0;
bearsrc.right = 56;
}
SystemClock.sleep(100);
count++;
if (count > 14) {
break;
}
}
SystemClock.sleep(2000);
}
void sqbear1() {
bearsrc.left = 0;
bearsrc.right = 56;
bearsrc.top = (56*4);
bearsrc.bottom = (56*5);
beardst.left = 600;
beardst.right = 656;
beardst.top = 260;
beardst.bottom = 316;
sqbear2();
}
public SurfaceViewer(Context context, AttributeSet attrs) {
super(context, attrs);
bgdst = new Rect();
charsrc = new Rect();
chardst = new Rect();
dogsrc = new Rect();
dogdst = new Rect();
bearsrc = new Rect();
beardst = new Rect();
dialogsrc = new Rect();
dialogdst = new Rect();
mansrc = new Rect();
mandst = new Rect();
mollysrc = new Rect();
mollydst = new Rect();
youngstarsrc = new Rect();
youngstardst = new Rect();
// TODO Auto-generated constructor stub
main = BitmapFactory.decodeResource(getResources(),
R.drawable.moviemysterycharacter);
bgd = BitmapFactory.decodeResource(getResources(),
R.drawable.background);
dog = BitmapFactory.decodeResource(getResources(),
R.drawable.dog);
bear = BitmapFactory.decodeResource(getResources(),
R.drawable.differentbears);
man1 = BitmapFactory.decodeResource(getResources(), R.drawable.man1);
dialog = BitmapFactory.decodeResource(getResources(), R.drawable.dialog1);
molly = BitmapFactory.decodeResource(getResources(), R.drawable.auntmollu);
youngstar = BitmapFactory.decodeResource(getResources(), R.drawable.auntmollu);
p = new Paint();
rstory = new Runnable() {
public void run() {
while(true) {
sequence1();
}
}
};
tstory = new Thread(rstory);
tstory.start();
dstory = new Runnable() {
public void run() {
while(true) {
sqdog1();
}
}
};
tdstory = new Thread(dstory);
tdstory.start();
dbear = new Runnable() {
public void run() {
while(true) {
sqbear1();
}
}
};
tbear = new Thread(dbear);
tbear.start();
dbear = new Runnable() {
public void run() {
while (true) {
sqyoungstar1();
}
}
};
tbear = new Thread(dbear);
tbear.start();
}
#Override
public boolean onTouch(View v, MotionEvent me) {
// TODO Auto-generated method stub
Intent i = new Intent(svc, SecondAct.class);
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
svc.startActivity(i);
break;
case MotionEvent.ACTION_UP:
svc.startActivity(i);
break;
}
return true;
}
}

Try to use getContext() instead of svc.

Related

solve game problems in Android Studio

For the university project, we have to solve the problems of a game. In the game that was given to me, there are many problems, for example, the spikes do not come down, the background is not displayed completely, the points and lives are not visible. Can someone help me? How can I use an activity instead of using Android view? Note: In this game, the first character must be saved and spikes will be thrown on him from the top of the screen, when the spikes hit the ground, an explosion will occur.
public class GameView extends View {
Bitmap background, ground, rabbit;
Rect recetBacground, rectGround;
Context context;
Handler handler;
final long UPDATE_MILLS = 30;
Runnable runnable;
Paint textPaint = new Paint();
Paint healthpaint = new Paint();
float TEXT_SIZE = 120;
int points = 0;
int life = 3;
static int dWidth, dHeight;
Random random;
float rabbitX, rabbitY;
float oldX;
float oldRabbitX;
ArrayList<Spike> spikes;
ArrayList<Explosion> explosions;
public GameView(Context context) {
super(context);
this.context = context;
background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
ground = BitmapFactory.decodeResource(getResources(), R.drawable.ground);
rabbit = BitmapFactory.decodeResource(getResources(), R.drawable.rabbit);
Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
dWidth = size.x;
dHeight = size.y;
recetBacground = new Rect(0, 0, dWidth, dHeight);
rectGround = new Rect(0, dHeight - ground.getHeight(), dWidth ,dHeight);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
invalidate();
}
};
textPaint.setColor(Color.rgb(255, 165, 0));
textPaint.setTextSize(TEXT_SIZE);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setTypeface(ResourcesCompat.getFont(context, R.font.pingiefont));
healthpaint.setColor(Color.GREEN);
random = new Random();
rabbitX = dWidth / 2 - rabbit.getWidth() / 2;
rabbitY = dHeight - ground.getHeight() - rabbit.getHeight();
spikes = new ArrayList<>();
explosions = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Spike spike = new Spike(context);
spikes.add(spike);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(background, null, recetBacground, null);
canvas.drawBitmap(ground, null, rectGround, null);
canvas.drawBitmap(rabbit, rabbitX, rabbitY, null);
for (int i = 0; i < spikes.size(); i++) {
canvas.drawBitmap(spikes.get(i).getSpike(spikes.get(i).spikeFarm), spikes.get(i).spikeX, spikes.get(i).spikeY, null);
spikes.get(i).spikeFarm++;
if (spikes.get(i).spikeFarm > 2) {
spikes.get(i).spikeFarm = 0;
}
spikes.get(i).spikeY += spikes.get(i).spikeVelocity;
if (spikes.get(i).spikeY + spikes.get(i).getSpikeHeight() >= dHeight - ground.getHeight()) {
points += 10;
Explosion explosion = new Explosion(context);
explosion.explosionX = spikes.get(i).spikeX;
explosion.explosionY = spikes.get(i).spikeY;
explosions.add(explosion);
spikes.get(i).resetPosition();
}
}
for (int i = 0; i < spikes.size(); i++) {
if(spikes.get(i).spikeX+spikes.get(i).getSikeWidth()>=rabbitX
&& spikes.get(i).spikeX <= rabbitX+rabbit.getWidth()
&& spikes.get(i).spikeY+spikes.get(i).getSikeWidth() >= rabbitY
&& spikes.get(i).spikeY+spikes.get(i).getSikeWidth()<= rabbitY +rabbit.getHeight()){
life--;
spikes.get(i).resetPosition();
if (life==0){
Intent intent=new Intent(context,GameOver.class);
intent.putExtra("points:",points);
context.startActivity(intent);
((Activity) context).finish();
}
}
}
for (int i=0;i<explosions.size();i++){
canvas.drawBitmap(explosions.get(i).getExplosion(explosions.get(i).explosionFarm),explosions.get(i).explosionX,
explosions.get(i).explosionY,null );
explosions.get(i).explosionFarm++;
if (explosions.get(i).explosionFarm>3){
explosions.remove(i);
}
}
if (life==2) {
healthpaint.setColor(Color.YELLOW);
}
else{
healthpaint.setColor(Color.RED);
}
canvas.drawRect(dWidth-200,30,dWidth-200+60*life,80,healthpaint);
canvas.drawText(""+points,20,TEXT_SIZE,textPaint);
handler.postDelayed(runnable,UPDATE_MILLS);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX=event.getX();
float touchY=event.getY();
if (touchY>= rabbitY){
int action = event.getAction();
if(action== MotionEvent.ACTION_DOWN){
oldX=event.getX();
oldRabbitX=rabbitX;
}
if(action==MotionEvent.ACTION_MOVE){
float shift = oldX- touchX;
float newRabbitX =oldRabbitX-shift;
if(newRabbitX<=0)
rabbitX=0;
else if (newRabbitX>=dWidth-rabbit.getWidth())
rabbitX = dWidth - rabbit.getWidth();
else
rabbitX=newRabbitX;
}
}
return true;
}
}
public class Spike {
Bitmap spike[] = new Bitmap[3];
int spikeFarm =0;
int spikeX,spikeY,spikeVelocity;
Random random;
public Spike(Context context){
spike[0]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike0);
spike[1]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike1);
spike[2]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike2);
random=new Random();
}
public Bitmap getSpike(int spikeFarm){
return spike[spikeFarm];
}
public int getSikeWidth(){
return spike[0].getWidth();
}
public int getSpikeHeight(){
return spike[0].getHeight();
}
public void resetPosition(){
spikeX=random.nextInt(GameView.dWidth-getSikeWidth());
spikeY=-200+random.nextInt(600)* -1;
spikeVelocity= 35+random.nextInt(16);
}
}

How to fill the color gradually on drawn view canvas Android

I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.

onDraw method not called in my application

i am developing an application, in that onDraw() is called. i am using the following logic.
so, please guide where i did the mistake.
MainActivity
public class Hello extends Activity implements SensorListener
{
private MyView myView;
private SensorManager sensorManager;
public void onAccuracyChanged(int paramInt1, int paramInt2)
{
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
Log.e("hello", "hello");
this.myView = new MyView(this);
setContentView(this.myView);
this.sensorManager = ((SensorManager)getSystemService("sensor"));
this.myView.setTheme(2);
}
protected void onResume()
{
super.onResume();
this.sensorManager.registerListener(this, 3, 0);
}
public void onSensorChanged(int paramInt, float[] paramArrayOfFloat)
{
switch (paramInt)
{
default:
case 1:
case 2:
}
this.myView.resetTama();
do
{
do
return;
while (Math.abs(paramArrayOfFloat[2]) <= 50.0F);
}
while (Math.abs(paramArrayOfFloat[0]) <= 15.0F);
}
public void onWindowFocusChanged(boolean paramBoolean)
{
super.onWindowFocusChanged(paramBoolean);
if (paramBoolean)
this.myView.init();
}
}
MyView class
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import java.lang.reflect.Array;
public class MyView extends RelativeLayout
{
private final int FP = -1;
private final int WC = -2;
public boolean disableApplication = false;
private int imgType = 1;
public boolean isBlack = false;
boolean isInitialized;
private Bitmap myBitmap;
private Paint myPaint = new Paint();
private int[] numbers;
private Tama[] oyatamaArray;
private Tama[][] tamaArray;
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.haikei);
setWillNotDraw(false);
this.myBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.tama);
this.numbers = new int[6];
for (int i = 0; i<numbers.length; i++)
{
if (i >= this.numbers.length)
{
loadChangeThemeButton(paramContext);
new TextView(paramContext).setBackgroundResource(R.drawable.bar);
return;
}
this.numbers[i] = 0;
}
}
private void changeBackgroundImage()
{
int i = 1 + this.imgType;
this.imgType = i;
if (i > 3)
this.imgType = 1;
setTheme(this.imgType);
}
private void loadChangeThemeButton(Context paramContext)
{
ImageButton localImageButton = new ImageButton(paramContext);
localImageButton.setBackgroundResource(R.drawable.themebutton);
RelativeLayout.LayoutParams localLayoutParams = new RelativeLayout.LayoutParams(-2, -2);
localLayoutParams.addRule(9);
localLayoutParams.addRule(12);
localLayoutParams.setMargins(0, 0, 30, 30);
addView(localImageButton, localLayoutParams);
localImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
MyView.this.changeBackgroundImage();
}
});
}
private Bitmap returnNumberImg(Resources paramResources, int paramInt)
{
switch (paramInt)
{
default:
return BitmapFactory.decodeResource(paramResources, R.drawable.n0);
case 1:
return BitmapFactory.decodeResource(paramResources, R.drawable.n1);
case 2:
return BitmapFactory.decodeResource(paramResources, R.drawable.n2);
case 3:
return BitmapFactory.decodeResource(paramResources, R.drawable.n3);
case 4:
return BitmapFactory.decodeResource(paramResources, R.drawable.n4);
case 5:
return BitmapFactory.decodeResource(paramResources, R.drawable.n5);
case 6:
return BitmapFactory.decodeResource(paramResources, R.drawable.n6);
case 7:
return BitmapFactory.decodeResource(paramResources, R.drawable.n7);
case 8:
return BitmapFactory.decodeResource(paramResources, R.drawable.n8);
case 9:
}
return BitmapFactory.decodeResource(paramResources, R.drawable.n9);
}
private void settingTamasTouchX(int paramInt1, int paramInt2)
{
int i = 0;
if (i >= this.oyatamaArray.length);
int k;
for (int j = 0; ; j++)
{
if (j >= this.tamaArray.length)
{
return;
}
k = 0;
if (k < this.tamaArray[j].length)
{
if (this.tamaArray[j][k].checkArea(paramInt1, paramInt2));
for (this.tamaArray[j][k].touchX = paramInt1; ; this.tamaArray[j][k].touchX = 0)
{
k++;
break;
}
// break label90;
}
}
}
public void init()
{
int i = getHeight() / 7;
int[] arrayOfInt = new int[6];
int j = 5;
if (j < 0)
this.oyatamaArray = new Tama[6];
int m;
int i1 = 0;
for (int k = 0; ; k++)
{
if (k >= this.oyatamaArray.length)
{
this.tamaArray = ((Tama[][])Array.newInstance(Tama.class, new int[] { 6, 4 }));
m = 0;
if (m < this.tamaArray.length)
{
for (int n = 0; ; n++)
{
if (n >= this.tamaArray[m].length)
{
m++;
break;
}
this.tamaArray[m][n] = new Tama(40 + n * 37, arrayOfInt[m] - 32, n + m * 10);
}
// break label154;
}
i1 = 0;
if (i1 < this.tamaArray.length)
{
for (int i2 = 0; ; i2++)
{
if (i2 >= this.tamaArray[i1].length)
{
i1++;
break;
}
if (i2 != this.tamaArray[i1].length - 1)
this.tamaArray[i1][i2].ueTama = this.tamaArray[i1][(i2 + 1)];
if (i2 == 0)
continue;
this.tamaArray[i1][i2].shitaTama = this.tamaArray[i1][(i2 - 1)];
}
// break label222;
}
this.isInitialized = true;
return;
}
this.oyatamaArray[k] = new Tama(279, arrayOfInt[k] - 32, k);
this.oyatamaArray[k].isOya = true;
}
}
#Override
protected void dispatchDraw(Canvas canvas){
super.dispatchDraw(canvas);
Log.e("......this.........","drawing");
}
#Override
protected void onDraw(Canvas paramCanvas)
{
super.onDraw(paramCanvas);
Log.e("This on draw","....yes");
if (!this.isInitialized)
init();
int i = 0;
Resources localResources;
int m;
while (true)
{
int j;
if (i >= this.oyatamaArray.length)
{
j = 0;
if (j >= this.tamaArray.length)
{
localResources = getContext().getResources();
m = 0;
if (m < 7)
break;
return;
}
}
else
{
paramCanvas.drawBitmap(this.myBitmap, this.oyatamaArray[i].getX(), this.oyatamaArray[i].getY(), this.myPaint);
i++;
continue;
}
for (int k = 0; ; k++)
{
if (k >= this.tamaArray[j].length)
{
j++;
break;
}
paramCanvas.drawBitmap(this.myBitmap, this.tamaArray[j][k].getX(), this.tamaArray[j][k].getY(), this.myPaint);
}
}
if (this.numbers.length <= m)
{
for (Bitmap localBitmap = BitmapFactory.decodeResource(localResources, 2130837523); ; localBitmap = returnNumberImg(localResources, this.numbers[m]))
{
paramCanvas.drawBitmap(localBitmap, 8.0F, getHeight() / 2 + m * 18, this.myPaint);
m++;
break;
}
}
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
int i = (int)paramMotionEvent.getX();
int j = (int)paramMotionEvent.getY();
if ((paramMotionEvent.getAction() == 0) && (i >= 0) && (i <= 40) && (410 <= j) && (j <= 430))
changeBackgroundImage();
if (paramMotionEvent.getAction() == 0)
settingTamasTouchX(i, j);
if (1 == paramMotionEvent.getAction())
settingTamasTouchX(0, 0);
int k;
int m = 0;
if (2 == paramMotionEvent.getAction())
{
k = 0;
if (k >= this.oyatamaArray.length)
{
m = 0;
if (m < this.tamaArray.length)
{
for (int n = 0; ; n++)
{
if (n >= this.tamaArray[m].length)
{
m++;
break;
}
this.tamaArray[m][n].checkAndSetArea(i, j);
if (!this.tamaArray[m][n].isUp)
continue;
int[] arrayOfInt = this.numbers;
arrayOfInt[m] = (1 + arrayOfInt[m]);
}
// break label164;
}
invalidate();
}
}
else
{
return true;
}
this.oyatamaArray[k].checkAndSetArea(i, j);
if (this.oyatamaArray[k].isUp)
this.numbers[k] = 5;
while (true)
{
k++;
break;
}
// label164:
return disableApplication;
}
public void resetTama()
{
int j;
for (int i = 0; ; i++)
{
if (i >= this.oyatamaArray.length)
{
j = 0;
if (j < this.tamaArray.length)
break;
invalidate();
return;
}
this.oyatamaArray[i].moveX(this.oyatamaArray[i].startX);
this.oyatamaArray[i].isUp = false;
this.numbers[i] = 0;
}
for (int k = 0; ; k++)
{
if (k >= this.tamaArray[j].length)
{
j++;
break;
}
this.tamaArray[j][k].moveX(this.tamaArray[j][k].startX);
this.tamaArray[j][k].isUp = false;
}
}
public void sensorChange(float[] paramArrayOfFloat)
{
int i = 0;
if (paramArrayOfFloat[2] < -50.0F)
i = 0 - 3;
int k;
while (true)
{
int j = 0;
if (j >= this.oyatamaArray.length)
{
k = 0;
if (k < this.tamaArray.length)
break;
if (i != 0)
invalidate();
return;
}
else
{
this.oyatamaArray[j].moveX(i + this.oyatamaArray[j].getX());
if (this.oyatamaArray[j].isUp)
this.numbers[j] = 5;
while (true)
{
j++;
break;
}
}
}
for (int m = 0; ; m++)
{
if (m >= this.tamaArray[k].length)
{
k++;
break;
}
this.tamaArray[k][m].moveX(i + this.tamaArray[k][m].getX());
if (!this.tamaArray[k][m].isUp)
continue;
int[] arrayOfInt = this.numbers;
arrayOfInt[k] = (1 + arrayOfInt[k]);
}
}
public void setTheme(int paramInt)
{
Resources localResources = getContext().getResources();
if (paramInt == 1)
{
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama);
setBackgroundResource(R.drawable.haikei);
}
while (true)
{
invalidate();
// return;
if (paramInt == 2)
{
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama2);
setBackgroundResource(2130837510);
continue;
}
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama3);
setBackgroundResource(2130837510);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="#id/FrameLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Try the below it works
To the question posted before edit.
If you're extending a ViewGroup you should override dispatchDraw() instead of onDraw().
Discussion on the topic #
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/oLccWfszuUo
public class Hello extends Activity {
private MyView myView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
Log.e("hello", "hello");
this.myView = new MyView(this);
setContentView(this.myView);
}
public class MyView extends RelativeLayout
{
private Paint myPaint = new Paint();
private int[] numbers;
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.ic_launcher);
}
#Override
protected void dispatchDraw(Canvas canvas){
super.dispatchDraw(canvas);
Log.i("...............","drawing");
}
}
}
protected void dispatchDraw (Canvas canvas)
Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).
Parameters
canvas the canvas on which to draw the view
If you Override onDraw inthe constructor call setWillNotDraw(false) then it should work.
http://developer.android.com/reference/android/view/View.html#setWillNotDraw(boolean)
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.ic_launcher);
setWillNotDraw(false);
}

Connecting 2 images in android

I want to connect 2 images in android. Example,
I want them to be like this,
I have already done it by hard coding. First I find the upper left of the green image and then find the the most lower left point of the green side.I do it with touch event's event.gerRawX() and event.getRawY() parameters. Now I know the distance in x and y between those two points. I do the similar thing for the red one too. Now when green piece is moved close to the red I just calculate if upper left point of red piece is near to the lower left of the green piece. if so I translate the green one/ red one to the other one. But this hard coded calculation should fail for same size tablet or phone with different resolution. I just want to know how do I generalize the solution. Thanks.
Edit: My GameActivity and ImageInfo class where I try to connect both images. I have actually 6 images like this. And i wanto connect them. Like image 1 will connect to image 2 and image 2 to 3 and so on.
GameActivity class
package com.example.JigSawPuzzle;
import com.example.test.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
#SuppressLint("NewApi")
public class GameActivity extends Activity implements OnTouchListener
{
static double screenInches;
int touchStartX = 0;
int touchStartY = 0;
int diffX = 0;
int diffY = 0;
int attachedPieces=0;
int imageX = 0;
int imageY = 0;
int height,width;
boolean [] flag = new boolean[7];
boolean isPortait;
RelativeLayout relataivelayoutLayout;
RelativeLayout.LayoutParams paramsA,paramsB,paramsC,paramsD,paramsE,paramsF;
ImageView imageA,imageB,imageC,imageD,imageE,imageF;
ImageInfo [] imageInfoArray = new ImageInfo[7];
// added for sound effect
private SoundPool soundPool;
private int correctPieceAttachSoundId,gameFinishSoundId;
private boolean loaded = false;
//for 10inch landscape height = 752, width = 1280; portrait height = 1232 width = 800
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
isPortait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ? false : true;
Display display = getWindowManager().getDefaultDisplay();
height = display.getHeight();
width = display.getWidth();
imageA = new ImageView(this);
imageB = new ImageView(this);
imageC = new ImageView(this);
imageD = new ImageView(this);
imageE = new ImageView(this);
imageF = new ImageView(this);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels/dm.xdpi,2);
double y = Math.pow(dm.heightPixels/dm.ydpi,2);
screenInches = Math.sqrt(x+y);
if(screenInches>9.0)
{
imageA.setBackgroundResource(R.drawable.a);
imageB.setBackgroundResource(R.drawable.b);
imageC.setBackgroundResource(R.drawable.c);
imageD.setBackgroundResource(R.drawable.d);
imageE.setBackgroundResource(R.drawable.e);
imageF.setBackgroundResource(R.drawable.f);
}
else
{
imageA.setBackgroundResource(R.drawable.aa);
imageB.setBackgroundResource(R.drawable.bb);
imageC.setBackgroundResource(R.drawable.cc);
imageD.setBackgroundResource(R.drawable.dd);
imageE.setBackgroundResource(R.drawable.ee);
imageF.setBackgroundResource(R.drawable.ff);
}
imageA.setId(1);
imageA.setTag("a");
paramsA = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageA.setLayoutParams(paramsA);
imageA.setOnTouchListener(this);
//Log.d("GameActivity", "")
imageB.setId(2);
imageB.setTag("b");
paramsB = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageB.setLayoutParams(paramsB);
imageB.setOnTouchListener(this);
imageC.setId(3);
imageC.setTag("c");
paramsC = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageC.setLayoutParams(paramsC);
imageC.setOnTouchListener(this);
imageD.setId(4);
imageD.setTag("d");
paramsD = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageD.setLayoutParams(paramsD);
imageD.setOnTouchListener(this);
imageE.setId(5);
imageE.setTag("e");
paramsE = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageE.setLayoutParams(paramsE);
imageE.setOnTouchListener(this);
imageF.setId(6);
imageF.setTag("f");
paramsF = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
imageF.setLayoutParams(paramsF);
imageF.setOnTouchListener(this);
setupPieces();
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
}
});
gameFinishSoundId = soundPool.load(this, R.raw.bells, 1);
correctPieceAttachSoundId= soundPool.load(this, R.raw.bell, 1);
}
public void playSound(int soundId)
{
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded)
{
soundPool.play(soundId, volume, volume, 1, 0, 1.0f);
}
}
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
// Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "in OnConfiguaration Changed", Toast.LENGTH_SHORT).show();
isPortait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ? false : true;
((RelativeLayout)imageA.getParent()).removeAllViews();
Log.d("GameActivity", "in onconfigurationChanged");
setupPieces();
}
public void setupPieces()
{
RelativeLayout relataivelayoutLayout = new RelativeLayout(this);
Display display = getWindowManager().getDefaultDisplay();
height = display.getHeight();
width = display.getWidth();
if(!isPortait)
{
paramsA.leftMargin = 10; //Your X coordinate
paramsA.topMargin = 30; //Your Y coordinate
}
else
{
paramsA.leftMargin = 30; //Your X coordinate
paramsA.topMargin = 10; //Your Y coordinate
}
imageA.setLayoutParams(paramsA);
imageA.setOnTouchListener(this);
//Log.d("GameActivity", "")
if(!isPortait)
{
paramsB.leftMargin = 650; //Your X coordinate
paramsB.topMargin = 300; //Your Y coordinate
}
else
{
paramsB.leftMargin = 300; //Your X coordinate
paramsB.topMargin = 750; //Your Y coordinate
}
imageB.setLayoutParams(paramsB);
imageB.setOnTouchListener(this);
if(!isPortait)
{
paramsC.leftMargin = 400; //Your X coordinate
paramsC.topMargin = 380; //Your Y coordinate
}
else
{
paramsC.leftMargin = 400; //Your X coordinate
paramsC.topMargin = 350; //Your Y coordinate
}
imageC.setLayoutParams(paramsC);
imageC.setOnTouchListener(this);
if(!isPortait)
{
paramsD.leftMargin = 750; //Your X coordinate
paramsD.topMargin = 20; //Your Y coordinate
}
else
{
paramsD.leftMargin = 20; //Your X coordinate
paramsD.topMargin = 750; //Your Y coordinate
}
imageD.setLayoutParams(paramsD);
imageD.setOnTouchListener(this);
if(!isPortait)
{
paramsE.leftMargin = 900; //Your X coordinate
paramsE.topMargin = 400; //Your Y coordinate
}
else
{
paramsE.leftMargin = 475; //Your X coordinate
paramsE.topMargin = 700; //Your Y coordinate
}
imageE.setLayoutParams(paramsE);
imageE.setOnTouchListener(this);
if(!isPortait)
{
paramsF.leftMargin = 90; //Your X coordinate
paramsF.topMargin = 300; //Your Y coordinate
}
else
{
paramsF.leftMargin = 90; //Your X coordinate
paramsF.topMargin = 300; //Your Y coordinate
}
imageF.setLayoutParams(paramsF);
imageF.setOnTouchListener(this);
ImageInfo imageAinfo = new ImageInfo(imageA.getId(),imageA,1,2);
imageInfoArray[0] = imageAinfo;
ImageInfo imageBinfo = new ImageInfo(imageB.getId(),imageB,1,3);
imageInfoArray[1] = imageBinfo;
ImageInfo imageCinfo = new ImageInfo(imageC.getId(),imageC,2,4);
imageInfoArray[2] = imageCinfo;
ImageInfo imageDinfo = new ImageInfo(imageD.getId(),imageD,3,5);
imageInfoArray[3] = imageDinfo;
ImageInfo imageEinfo = new ImageInfo(imageE.getId(),imageE,4,6);
imageInfoArray[4] = imageEinfo;
ImageInfo imageFinfo = new ImageInfo(imageF.getId(),imageF,5,6);
imageInfoArray[5] = imageFinfo;
relataivelayoutLayout.addView(imageA);
relataivelayoutLayout.addView(imageB);
relataivelayoutLayout.addView(imageC);
relataivelayoutLayout.addView(imageD);
relataivelayoutLayout.addView(imageE);
relataivelayoutLayout.addView(imageF);
setContentView(relataivelayoutLayout);
}
private void updatePosition(int id)
{
if(flag[imageInfoArray[id-1].id])
return;
flag[imageInfoArray[id-1].id] = true;
RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams)imageInfoArray[id-1].imageView.getLayoutParams();
param.leftMargin = imageInfoArray[id-1].imageView.getLeft() + diffX;
param.topMargin = imageInfoArray[id-1].imageView.getTop() + diffY;
imageInfoArray[id-1].imageView.setLayoutParams(param);
if(imageInfoArray[id-1].isTopConnected)
updatePosition(imageInfoArray[id-1].topPieceId);
if(imageInfoArray[id-1].isBottomConnected)
updatePosition(imageInfoArray[id-1].bottomPieceId);
return;
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(v instanceof ImageView)
{
ImageView imageView = (ImageView) v;
ImageInfo imageInfo = imageInfoArray[imageView.getId()-1];
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
touchStartX = (int) event.getRawX();
touchStartY = (int) event.getRawY();
imageX = imageView.getLeft();
imageY = imageView.getTop();
//Toast.makeText(this, "x = "+event.getRawX()+" y = "+event.getRawY(), Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_UP:
touchStartX = (int) event.getRawX();
touchStartY = (int) event.getRawY();
imageX = imageView.getLeft();
imageY = imageView.getTop();
int id = imageInfo.id;
while(imageInfo.isTopConnected)
{
if(imageInfo.id == imageInfo.topPieceId)
break;
imageInfo = imageInfoArray[imageInfo.topPieceId-1];
}
if(!imageInfo.isTopConnected)
{
imageView = imageInfo.imageView;
int topConnectingPieceId = imageInfo.topPieceId;
int topConnectingX=0,topConnectingY=0;
topConnectingX = imageInfo.calculateTopX(imageView.getLeft(), imageView.getId());
topConnectingY = imageInfo.calculateTopY(imageView.getTop(), imageView.getId());
ImageInfo topImageInfo = imageInfoArray[topConnectingPieceId-1];
int bottomConnectingX = topImageInfo.calculateBottomX(topImageInfo.imageView.getLeft(),topConnectingPieceId);
int bottomConnectingY = topImageInfo.calculateBottomY(topImageInfo.imageView.getTop(),topConnectingPieceId);
diffX = (bottomConnectingX-topConnectingX);
diffY = (bottomConnectingY-topConnectingY);
if(Math.abs(diffX)<=20 && Math.abs(diffY)<=20)
{
for(int i=0;i<7;i++)
flag[i]=false;
updatePosition(imageInfo.id);
imageInfo.setIsTopConnected(true);
topImageInfo.setIsBottomConnected(true);
attachedPieces++;
if(attachedPieces==5)
{
setupFinishDialogue();
playSound(gameFinishSoundId);
}
else
playSound(correctPieceAttachSoundId);
break;
}
}
imageInfo = imageInfoArray[id-1];
while(imageInfo.isBottomConnected)
{
if(imageInfo.id == imageInfoArray[imageInfo.bottomPieceId-1].id)
break;
imageInfo = imageInfoArray[imageInfo.bottomPieceId-1];
}
imageView = imageInfo.imageView;
if(!imageInfo.isBottomConnected)
{
int topConnectingX=0,topConnectingY=0;
int bottomConnectingX = imageInfo.calculateBottomX(imageView.getLeft(), imageView.getId());
int bottomConnectingY = imageInfo.calculateBottomY(imageView.getTop(), imageView.getId());
int bottomConnectingPieceId = imageInfo.bottomPieceId;
ImageInfo bottomImageInfo = imageInfoArray[bottomConnectingPieceId-1];
topConnectingX = bottomImageInfo.calculateTopX(bottomImageInfo.imageView.getLeft(),bottomConnectingPieceId);
topConnectingY = bottomImageInfo.calculateTopY(bottomImageInfo.imageView.getTop(), bottomConnectingPieceId);
diffX = (topConnectingX-bottomConnectingX);
diffY = (topConnectingY-bottomConnectingY);
if(Math.abs(diffX)<=20 && Math.abs(diffY)<=20)
{
for(int i=0;i<7;i++)
flag[i]=false;
updatePosition(imageInfo.id);
imageInfo.setIsBottomConnected(true);
bottomImageInfo.setIsTopConnected(true);
attachedPieces++;
if(attachedPieces==5)
{
setupFinishDialogue();
playSound(gameFinishSoundId);
}
else
playSound(correctPieceAttachSoundId);
}
}
break;
case MotionEvent.ACTION_MOVE:
diffX = (int) (event.getRawX() - touchStartX);
diffY = (int) (event.getRawY() - touchStartY);
touchStartX = (int)event.getRawX();
touchStartY = (int)event.getRawY();
for(int i=0;i<7;i++)
flag[i]=false;
updatePosition(imageInfo.id);
break;
default:
break;
}
}
return true;
}
void lockOrientation()
{
switch (getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_PORTRAIT:
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.FROYO)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else
{
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if(rotation == android.view.Surface.ROTATION_90|| rotation == android.view.Surface.ROTATION_180)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
break;
case Configuration.ORIENTATION_LANDSCAPE:
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.FROYO)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else
{
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if(rotation == android.view.Surface.ROTATION_0 || rotation == android.view.Surface.ROTATION_90){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
}
break;
}
}
void setupFinishDialogue()
{
/*if(getWindowManager().getDefaultDisplay().getRotation()==3)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else if(getWindowManager().getDefaultDisplay().getRotation()==1)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
else if(getWindowManager().getDefaultDisplay().getRotation()==2)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);*/
lockOrientation();
AlertDialog.Builder builderForAlertBox = new AlertDialog.Builder(this);
builderForAlertBox.setCancelable(false).setMessage("Good Job!").setPositiveButton("Restart", dialogClickListner).setNegativeButton("Quit", dialogClickListner).
setCancelable(true).show();
}
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
finish();
Intent intent = new Intent(getApplicationContext(),GameActivity.class);
startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
default:
break;
}
}
};
}
ImageInfo Class
package com.example.JigSawPuzzle;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageInfo
{
ImageView imageView;
int imageATopLeftDifferenceX = -1;
int imageATopLeftDifferenceY = -1;
int imageABottomRightDifferenceX = 113;
int imageABottomRightDifferenceY = 140;
int imageBTopLeftDifferenceX = 0;
int imageBTopLeftDifferenceY = 0;
int imageBBottomRightDifferenceX = 0;
int imageBBottomRightDifferenceY = 111;
int imageCTopLeftDifferenceX = 14;
int imageCTopLeftDifferenceY = 0;
int imageCBottomRightDifferenceX = 0;
int imageCBottomRightDifferenceY = 88;
int imageDTopLeftDifferenceX = 92;
int imageDTopLeftDifferenceY = 2;
int imageDBottomRightDifferenceX = 0;
int imageDBottomRightDifferenceY = 70;
/*int imageETopLeftDifferenceX = 0;
int imageETopLeftDifferenceY = 0;
int imageEBottomRightDifferenceX = 55;
int imageEBottomRightDifferenceY = 112;*/
int imageETopLeftDifferenceX = 55;
int imageETopLeftDifferenceY = 112;
int imageEBottomRightDifferenceX = 0;
int imageEBottomRightDifferenceY = 0;
/*int imageFTopLeftDifferenceX = 0;
int imageFTopLeftDifferenceY = 26;
int imageFBottomRightDifferenceX = 0;
int imageFBottomRightDifferenceY = 109;
int id,topPieceId,bottomPieceId;*/
int imageFTopLeftDifferenceX = 0;
int imageFTopLeftDifferenceY = 109;
int imageFBottomRightDifferenceX = 0;
int imageFBottomRightDifferenceY = 26;
int id,topPieceId,bottomPieceId;
boolean isTopConnected = false;
boolean isBottomConnected = false;
public ImageInfo(int id,ImageView imageView,int topPieceId,int bottomPieceId)
{
this.topPieceId = topPieceId;
this.bottomPieceId = bottomPieceId;
this.imageView = imageView;
this.id = id;
if(id==1)
isTopConnected = true;
else if(id==6)
isBottomConnected = true;
if(GameActivity.screenInches>9.0)
initializePiecesInfo();
}
private void initializePiecesInfo()
{
imageATopLeftDifferenceX = 0;
imageATopLeftDifferenceY = 0;
imageABottomRightDifferenceX = 150;
imageABottomRightDifferenceY = 184;
imageBTopLeftDifferenceX = 0;
imageBTopLeftDifferenceY = 0;
imageBBottomRightDifferenceX = 0;
imageBBottomRightDifferenceY = 148;
imageCTopLeftDifferenceX = 23;
imageCTopLeftDifferenceY = 0;
imageCBottomRightDifferenceX = 0;
imageCBottomRightDifferenceY = 115;
imageDTopLeftDifferenceX = 121;
imageDTopLeftDifferenceY = 0;
imageDBottomRightDifferenceX = 0;
imageDBottomRightDifferenceY = 91;
/*int imageETopLeftDifferenceX = 0;
int imageETopLeftDifferenceY = 0;
int imageEBottomRightDifferenceX = 55;
int imageEBottomRightDifferenceY = 112;*/
imageETopLeftDifferenceX = 74;
imageETopLeftDifferenceY = 147;
imageEBottomRightDifferenceX = 0;
imageEBottomRightDifferenceY = 0;
/*int imageFTopLeftDifferenceX = 0;
int imageFTopLeftDifferenceY = 26;
int imageFBottomRightDifferenceX = 0;
int imageFBottomRightDifferenceY = 109;
int id,topPieceId,bottomPieceId;*/
imageFTopLeftDifferenceX = 0;
imageFTopLeftDifferenceY = 144;
imageFBottomRightDifferenceX = 0;
imageFBottomRightDifferenceY = 26;
}
int calculateTopX(int realX,int id)
{
if(id==2)
return realX+imageBTopLeftDifferenceX;
if(id==3)
return realX+imageCTopLeftDifferenceX;
if(id==4)
return realX+imageDTopLeftDifferenceX;
if(id==5)
return realX+imageETopLeftDifferenceX;
if(id==6)
return realX+imageFTopLeftDifferenceX;
return realX;
}
int calculateTopY(int realY,int id)
{
if(id==2)
return realY+imageBTopLeftDifferenceY;
if(id==3)
return realY+imageCTopLeftDifferenceY;
if(id==4)
return realY+imageDTopLeftDifferenceY;
if(id==5)
return realY+imageETopLeftDifferenceY;
if(id==6)
return realY+imageFTopLeftDifferenceY;
return realY;
}
int calculateBottomX(int realX,int id)
{
if(id==1)
return realX+imageABottomRightDifferenceX;
if(id==2)
return realX+imageBBottomRightDifferenceX;
if(id==3)
return realX+imageCBottomRightDifferenceX;
if(id==4)
return realX+imageDBottomRightDifferenceX;
if(id==5)
return realX+imageEBottomRightDifferenceX;
return realX+imageFBottomRightDifferenceX;
}
int calculateBottomY(int realY,int id)
{
if(id==1)
return realY+imageABottomRightDifferenceY;
if(id==2)
return realY+imageBBottomRightDifferenceY;
if(id==3)
return realY+imageCBottomRightDifferenceY;
if(id==4)
return realY+imageDBottomRightDifferenceY;
if(id==5)
return realY+imageEBottomRightDifferenceY;
return realY+imageFBottomRightDifferenceY;
}
void setIsTopConnected(boolean isTopConnected)
{
this.isTopConnected = isTopConnected;
}
void setIsBottomConnected(boolean isBottomConnected)
{
this.isBottomConnected = isBottomConnected;
}
}
Given the images you provided it is straightforward to connect them in a generic way because the images have the same width and they have transparent background, here is the idea:
1- You need the overlap distance between the two images, which you can calculate from either the bottom or top image
The green line in the bottom picture should be equal to the red line in the top picture
Given that your images have transparent background you can calculate this distance easily, I will use the bottom image here.
The idea is to check every pixel in the last column of the bottom bitmap (i.e. width - 1) and stop once you hit a non-transparent pixel.
private int getOverlapDistance(Bitmap bottomBitmap) {
int height = bottomBitmap.getHeight();
int width = bottomBitmap.getWidth();
int distance = 0;
for (int i = 0; i < height; i++) {
if (Color.alpha(bottomBitmap.getPixel(width - 1, i)) != 0) {
distance = (i + 1);
break;
}
}
return distance;
}
To connect them you can do something like (assuming you have separate ImageView for the top and bottom image):
bitmap = ((BitmapDrawable) bottomImage.getDrawable()).getBitmap();
int overlapDistance = getOverlapDistance(bitmap);
bottomImage.setTop(topImage.getBottom() - overlapDistance);
Actually I tried this with a simple activity and it is working, here is how it look like before and after connecting the two images:
I just execute the above code when the button connect is clicked

Visual defects when I use drawBitmap()

It looks like this both in the emulator and on the phone. It's always a random square that is broken.
And here is the code from the SurfaceView class, the most relevant part is in prepareBackground() :
Code begins:
public class MenuBackgroundView extends SurfaceView implements SurfaceHolder.Callback
{
private Paint mPaint;
private Bitmap blocks12x12;
private boolean draw = false;
private Context ctx;
//private int begOffX;
private int offX;
private int offY;
private int mWidth = 1;
private int mHeight = 1;
private ViewThread mThread;
private int calcSizeXY;
public MenuBackgroundView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
mThread = new ViewThread(this);
mPaint = new Paint();
mPaint.setColor(Color.RED);
ctx = context;
}
public void doDraw(long elapsed, Canvas canvas) {
canvas.drawColor(Color.BLUE);
if(draw)
{
canvas.drawBitmap(blocks12x12, offX, offY, mPaint);
}
canvas.drawText("FPS: " + Math.round(1000f / elapsed) + " Elements: ", 10, 10, mPaint);
}
public void animate(long elapsed)
{
/*
//elapsed = elapsed/10;
offX = (offX+2);
if(offX >= 0)
{
offX -= 2*calcSizeXY;
}
offY = (offY+3);
if(offY >= 0)
{
offY -= 2*calcSizeXY;
}
//offY = (offY + (int)(elapsed/10f)) % calcSizeXY*2;//
*
*///
}
public void prepareBackground()
{
if(mWidth <= 1 || mHeight <= 1 )
return;
Log.d("Menu", "prepareBackground");
if(mHeight > mWidth)
{
calcSizeXY = mHeight/10;
}
else
{
calcSizeXY = mWidth/10;
}
offX = -2*calcSizeXY;
Bitmap block = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.block);
block = Bitmap.createScaledBitmap(block, calcSizeXY, calcSizeXY, false);
// Group together
int sizeX = 12*calcSizeXY;
int sizeY = 12*calcSizeXY;
blocks12x12 = Bitmap.createBitmap(sizeX, sizeY, Bitmap.Config.ARGB_8888);
Canvas blocks12x12Canvas = new Canvas(blocks12x12);
for(int i = 0; i < 14; i+=2)
{
for(int j = 0; j < 14; j+=2)
{
blocks12x12Canvas.drawBitmap(block, (j*calcSizeXY), (i*calcSizeXY), mPaint);
}
}
// "Memory leak"
block.recycle();
draw = true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
mWidth = width;
mHeight = height;
prepareBackground();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
prepareBackground();
if (!mThread.isAlive()) {
mThread = new ViewThread(this);
mThread.setRunning(true);
mThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mThread.isAlive()) {
mThread.setRunning(false);
freeMem();
}
}
public void freeMem() {
// TODO Auto-generated method stub
draw = false;
blocks12x12.recycle(); // "Memory leak"
}
}
Ok I figured it out, simply make the thread sleep for 1ms:
blocks12x12 = Bitmap.createBitmap(sizeX, sizeY, Bitmap.Config.ARGB_8888);
Canvas blocks12x12Canvas = new Canvas(blocks12x12);
for(int i = 0; i < 14; i+=2)
{
for(int j = 0; j < 14; j+=2)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
blocks12x12Canvas.drawBitmap(block, (j*calcSizeXY), (i*calcSizeXY), mPaint);
}
}

Categories

Resources