How to make a simple touch screen test application? - android

I want to make a simple touch screen test application like Samsung Device Diagnostic Tool.
A screenshot from Samsung Device Diagnostic Tool: http://i.stack.imgur.com/7KgKW.jpg
I'm not very familiar with Android App Development. Which way would you suggest me to make a simple application like the tool I mentioned above?

The development of this application easy matter. You need to understand:
How to get the coordinates of click.
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)(event.getX()/tileSize);
int y = (int)(event.getY()/tileSize);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
map[x][y] = true;
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
return false;
}
Override method onDraw, to draw rectangles.
private void init(){
tileSize = 10;
paint1 = new Paint();
paint1.setColor(Color.BLUE);
paint1.setStrokeWidth(10);
paint1.setStyle(Paint.Style.STROKE);
paint2 = new Paint();
paint2.setColor(Color.RED);
paint2.setStrokeWidth(10);
paint2.setStyle(Paint.Style.STROKE);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
Paint p = null;
if(map[i][j]){
p=paint1;
}else{
p=paint2;
}
canvas.drawRect(i*tileSize, j*tileSize, tileSize, tileSize, paint);
}
}
}
}

Recently I also had to make this screen test in my app. So I had figured a solution. I am taking an array of RectF i.e. ArrayList<RectF> arr = new ArrayList<>() and drawing this Rects in following order :
Left vertical line
private void drawLeftLine(int width, int height) {
int leftPoint = 0;
int topPoint = 0;
int rightPoint = 100;
int bottomPoint = 100;
int maxNoOfRect = height / 100;
int lastRectHeight = height % 100;
for (int i = 0; i < maxNoOfRect; i++) {
arr.add(new RectF(leftPoint, topPoint, rightPoint, bottomPoint));
topPoint = bottomPoint;
bottomPoint = bottomPoint + 100;
}
}
Top Horizontal line
private void drawTopLine(int w, int h) {
int leftPoint = 0;
int topPoint = 0;
int rightPoint = 100;
int bottomPoint = 100;
int maxNoOfRect = w / 100;
int lastRectWidth = w % 100;
for (int i = 0; i < maxNoOfRect; i++) {
arr.add(new RectF(leftPoint, topPoint, rightPoint, bottomPoint));
leftPoint = rightPoint;
rightPoint = rightPoint + 100;
}
arr.add(new RectF(leftPoint, topPoint, rightPoint + lastRectWidth, bottomPoint));
}
and similarly; 3. Right vertical line 4. Bottom horizontal line, with the help of collections of RectF of size 100.
So, when user touch a point, check whether that co-ordinate lies in any of the RectF bounds? If yes, remove that RectF from the array.
like :
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mOnViewTouchedListener != null)
mOnViewTouchedListener.onViewTouched();
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
Log.d("TAG", "point: " + point);
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(point.x, point.y)) {
Log.d("TAG", "Touch IN");
arr.remove(i);
invalidate();
break;
}
}
break;
case MotionEvent.ACTION_MOVE:
if (mOnViewTouchedListener != null)
mOnViewTouchedListener.onViewTouched();
Log.d("TAG", "ACTION_MOVE");
Point point1 = new Point();
point1.x = (int) event.getX();
point1.y = (int) event.getY();
Log.d("TAG", "point: " + point1);
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(point1.x, point1.y)) {
Log.d("TAG", "Touch IN");
arr.remove(i);
invalidate();
break;
}
}
break;
default:
return false;
}
return true;
}
So, this is the solution for this. Same way the diagonal lines are also drawn.
Diagonal line from top left to bottom right :
private void drawTBDiagonalLine(int w, int h) {
float height = h;
float width = w;
float slope = (height / width);
float left = 0;
float top = 0;
float bottom = 100;
float right = bottom / slope;
int maxNoOfRect = h / 100;
for (int i = 0; i < maxNoOfRect; i++) {
arr.add(new RectF(left, top, right, bottom));
left = right;
top = bottom;
bottom = bottom + 100;
right = bottom / slope;
}
}

Related

How to show previous Path on canvas when scrolling pages in android?

I have pdf file and I am drawing a path on devious canvas.And I try to show the previous canvas when scrolling the pdf pages.For that I am saving pdf page number and path.
My code :
This is onTouch: in ACTION_DOWN I am creating new constructor for path every time.When it's calling new path was removing old path and overriding on old path.If I removing this paths are working fine.
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
signaturePaint = new Paint(Paint.DITHER_FLAG);
signaturePaint.setAntiAlias(true);
signaturePaint.setDither(true);
signaturePaint.setColor(0xff0000cc);
signaturePaint.setStyle(Paint.Style.STROKE);
signaturePaint.setStrokeJoin(Paint.Join.ROUND);
signaturePaint.setStrokeCap(Paint.Cap.ROUND);
signaturePaint.setStrokeWidth(1);
**signaturePath = new Path();// When calling this my problem occure**
if (Constants.draw) {
Point p = getPagePositionOnScreen(currentPage);
int currentPageWidth = getCurrentPageWidth(currentPage);
int currentPageHeight = (int) getCurrentPageHeight(currentPage);
if (currentPageWidth < x || currentPageHeight < y) {
} else {
if (Constants.isSignatureSelected)
signaturePath.moveTo(x, y);
// pdfcanvas.moveTo(x, y);
}
firstX = x;
firstY = y;
}
break;
case MotionEvent.ACTION_MOVE:
if (Constants.draw) {
mPageNumber.add(currentPage);
// int[][] currentPagesSize = pagesProvider.getPageSizes();
float pageMarginX = getCurrentMarginX();
float pageMarginy = getCurrentMarginY();
// int pageWidth = currentPagesSize[0][0];
// int pageHeight = currentPagesSize[0][1];
int currentPageWidth = getCurrentPageWidth(currentPage);
int currentPageHeight = (int) getCurrentPageHeight(currentPage);
if (currentPageWidth < x || currentPageHeight < y) {
} else {
resetDirtyRect(x, y);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
if (Constants.isSignatureSelected)
signaturePath.lineTo(historicalX, historicalY);
}
}
}
break;
case MotionEvent.ACTION_UP:
if (Constants.draw) {
firstX = x;
firstY = y;
if (Constants.isSignatureSelected)
saveCanvas();
}
break;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
firstX = x;
firstY = y;
return true;
For savingCanvas in array list : this is saving my canvas paths in arraylist
private void saveCanvas() {
SaveCanvasDrawing canvasDrawing = new SaveCanvasDrawing();
canvasDrawing.setPath(signaturePath);
canvasDrawing.setPdfPageNumber(currentPage);
canvasDrawing.setxAxis(firstX);
canvasDrawing.setyAxis(firstY);
mSavingCanvasDrawing.add(canvasDrawing);
mCanvasHashMap.put(currentPage, mSavingCanvasDrawing);
}
For showing Paths on canvas : In this method in else block I am reseting path.When I am calling this canvas is not drawing my paths.But at the time of debugging my path not null.But it's not showing path on canvas.
private void redoCanvas() {
if (mCanvasHashMap.containsKey(currentPage)) {
mDrawingPath.clear();
mPageNumber.clear();
for (int j = 0; j < mSavingCanvasDrawing.size(); j++) {
int pageNumber = mSavingCanvasDrawing.get(j).getPdfPageNumber();
if (pageNumber == currentPage) {
float xAxis = mSavingCanvasDrawing.get(j).getxAxis();
float yAxis = mSavingCanvasDrawing.get(j).getyAxis();
Path path = mSavingCanvasDrawing.get(j).getPath();
mDrawingPath.add(path);
mPageNumber.add(pageNumber);
} else {
signaturePath.reset();
invalidate();
}
}
} else {
signaturePath.reset();
invalidate();
}
}
Finally onDraw() :
In this method I am checking when my isSignatureSelected = false; I am calling my saved arraylist for path and I am drawing.Here my problem was when I am reseting path in redoCanvas() it's not showing any paths on canvas.But if I remove those resetting lines canvas showng my paths but it's taking all paths from signaturePath.
protected void onDraw(Canvas canvas) {
if (Constants.isSignatureSelected) {
if (Constants.draw) {
canvas.drawPath(signaturePath, signaturePaint);
}
} else {
if (mPageNumber.contains(currentPage)) {
for (Path p : mDrawingPath) {
canvas.drawPath(p, signaturePaint);
}
}
}
}
Yes I got solution.In computeScroll() I am creating new constructor of Path and in onDraw() I am checking the my array list of paths and I am adding paths into canvas

Android Donut Chart

I have created a donut chart, which is shown below:
MY resultant Donut chart should be in the following way:
My Question is, How can i achieve the lines with image (They are rounded off in second screen shot)
For reference, Here is the code which I have written:
public class PieChartView extends View {
private int[] values = {30, 60, 90, 100, 150};
private int c[] = {Color.MAGENTA,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW};
private int valuesLength = values.length;
private RectF rectF;
private Paint slicePaint, textPaint;
private Path path;
public PieChartView(Context context, AttributeSet attrs) {
super(context, attrs);
valuesLength = values.length;
slicePaint = new Paint();
slicePaint.setAntiAlias(true);
slicePaint.setDither(true);
slicePaint.setStyle(Paint.Style.FILL);
path = new Path();
}
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(Canvas canvas) {
if(values != null) {
int startTop = 0;
int startLeft = 0;
int endBottom = getHeight();
int endRight = endBottom;// This makes an equal square.
rectF = new RectF(startLeft, startTop, endRight, endBottom);
float[] scaledValues = scale();
float sliceStartPoint = 0;
path.addCircle(rectF.centerX(), rectF.centerY(), 125, Direction.CW);
canvas.clipPath(path, Op.DIFFERENCE);
for(int i = 0; i < valuesLength; i++) {
slicePaint.setColor(c[i]);
path.reset();
path.addArc(rectF, sliceStartPoint, scaledValues[i]);
path.lineTo(rectF.centerX(), rectF.centerY());
canvas.drawPath(path, slicePaint);
sliceStartPoint += scaledValues[i];//This updates the starting point of next slice.
}
}
}
private float[] scale() {
float[] scaledValues = new float[this.values.length];
float total = getTotal(); //Total all values supplied to the chart
for (int i = 0; i < this.values.length; i++) {
scaledValues[i] = (this.values[i] / total) * 360; //Scale each value
}
return scaledValues;
}
private float getTotal() {
float total = 0;
for (float val : this.values)
total += val;
return total;
}
}
Also, How can I find out a co-ordinate from an angle(Start or sweep angle). If i want to draw a line from centre of a circle to the coordinate?
Here's how i finally did it after two days of search with help of this library https://github.com/Ken-Yang/AndroidPieChart
And equations to center text done with help of my friends and alot of search
on MainActivity onCreate or oncreateView if you are using fragments:
PieChart pie = (PieChart) rootView.findViewById(R.id.pieChart);
ArrayList<Float> alPercentage = new ArrayList<Float>();
alPercentage.add(2.0f);
alPercentage.add(8.0f);
alPercentage.add(20.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.85f);
alPercentage.add(9.15f);
try {
// setting data
pie.setAdapter(alPercentage);
// setting a listener
pie.setOnSelectedListener(new OnSelectedLisenter() {
#Override
public void onSelected(int iSelectedIndex) {
Toast.makeText(getActivity(),
"Select index:" + iSelectedIndex,
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
if (e.getMessage().equals(PieChart.ERROR_NOT_EQUAL_TO_100)) {
Log.e("kenyang", "percentage is not equal to 100");
}
}
public class PieChart extends View {
public interface OnSelectedLisenter {
public abstract void onSelected(int iSelectedIndex);
}
private OnSelectedLisenter onSelectedListener = null;
private static final String TAG = PieChart.class.getName();
public static final String ERROR_NOT_EQUAL_TO_100 = "NOT_EQUAL_TO_100";
private static final int DEGREE_360 = 360;
private static String[] PIE_COLORS = null;
private static int iColorListSize = 0;
ArrayList<Float> array;
private Paint paintPieFill;
private Paint paintPieBorder;
private Paint paintCenterCircle;
private ArrayList<Float> alPercentage = new ArrayList<Float>();
private int mCenterX = 320;
private int mCenterY = 320;
private int iDisplayWidth, iDisplayHeight;
private int iSelectedIndex = -1;
private int iCenterWidth = 0;
private int iShift = 0;
private int iMargin = 0; // margin to left and right, used for get Radius
private int iDataSize = 0;
private Canvas canvas1;
private RectF r = null;
private RectF centerCircle = null;
private float fDensity = 0.0f;
private float fStartAngle = 0.0f;
private float fEndAngle = 0.0f;
float fX;
float fY;
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
PIE_COLORS = getResources().getStringArray(R.array.colors);
iColorListSize = PIE_COLORS.length;
array = new ArrayList<Float>();
fnGetDisplayMetrics(context);
iShift = (int) fnGetRealPxFromDp(30);
iMargin = (int) fnGetRealPxFromDp(40);
centerCircle = new RectF(200, 200, 440, 440);
// used for paint circle
paintPieFill = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieFill.setStyle(Paint.Style.FILL);
// used for paint centerCircle
paintCenterCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
paintCenterCircle.setStyle(Paint.Style.FILL);
paintCenterCircle.setColor(Color.WHITE);
// used for paint border
paintPieBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieBorder.setStyle(Paint.Style.STROKE);
paintPieBorder.setStrokeWidth(fnGetRealPxFromDp(3));
paintPieBorder.setColor(Color.WHITE);
Log.i(TAG, "PieChart init");
}
// set listener
public void setOnSelectedListener(OnSelectedLisenter listener) {
this.onSelectedListener = listener;
}
float temp = 0;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i(TAG, "onDraw");
float centerX = (r.left + r.right) / 2;
float centerY = (r.top + r.bottom) / 2;
float radius1 = (r.right - r.left) / 2;
radius1 *= 0.5;
float startX = mCenterX;
float startY = mCenterY;
float radius = mCenterX;
float medianAngle = 0;
Path path = new Path();
for (int i = 0; i < iDataSize; i++) {
// check whether the data size larger than color list size
if (i >= iColorListSize) {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i
% iColorListSize]));
} else {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i]));
}
fEndAngle = alPercentage.get(i);
// convert percentage to angle
fEndAngle = fEndAngle / 100 * DEGREE_360;
// if the part of pie was selected then change the coordinate
if (iSelectedIndex == i) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
float fAngle = fStartAngle + fEndAngle / 2;
double dxRadius = Math.toRadians((fAngle + DEGREE_360)
% DEGREE_360);
fY = (float) Math.sin(dxRadius);
fX = (float) Math.cos(dxRadius);
canvas.translate(fX * iShift, fY * iShift);
}
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieFill);
float angle = (float) ((fStartAngle + fEndAngle / 2) * Math.PI / 180);
float stopX = (float) (startX + (radius/2) * Math.cos(angle));
float stopY = (float) (startY + (radius/2) * Math.sin(angle));
// if the part of pie was selected then draw a border
if (iSelectedIndex == i) {
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieBorder);
canvas.drawLine(startX, startY, stopX, stopY, paintPieFill);
canvas.restore();
}
fStartAngle = fStartAngle + fEndAngle;
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// get screen size
iDisplayWidth = MeasureSpec.getSize(widthMeasureSpec);
iDisplayHeight = MeasureSpec.getSize(heightMeasureSpec);
if (iDisplayWidth > iDisplayHeight) {
iDisplayWidth = iDisplayHeight;
}
/*
* determine the rectangle size
*/
iCenterWidth = iDisplayWidth / 2;
int iR = iCenterWidth - iMargin;
if (r == null) {
r = new RectF(iCenterWidth - iR, // top
iCenterWidth - iR, // left
iCenterWidth + iR, // right
iCenterWidth + iR); // bottom
}
if (centerCircle == null) {
// centerCircle=new RectF(left, top, right, bottom);
}
setMeasuredDimension(iDisplayWidth, iDisplayWidth);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// get degree of the touch point
double dx = Math.atan2(event.getY() - iCenterWidth, event.getX()
- iCenterWidth);
float fDegree = (float) (dx / (2 * Math.PI) * DEGREE_360);
fDegree = (fDegree + DEGREE_360) % DEGREE_360;
// get the percent of the selected degree
float fSelectedPercent = fDegree * 100 / DEGREE_360;
// check which pie was selected
float fTotalPercent = 0;
for (int i = 0; i < iDataSize; i++) {
fTotalPercent += alPercentage.get(i);
if (fTotalPercent > fSelectedPercent) {
iSelectedIndex = i;
break;
}
}
if (onSelectedListener != null) {
onSelectedListener.onSelected(iSelectedIndex);
}
invalidate();
return super.onTouchEvent(event);
}
private void fnGetDisplayMetrics(Context cxt) {
final DisplayMetrics dm = cxt.getResources().getDisplayMetrics();
fDensity = dm.density;
}
private float fnGetRealPxFromDp(float fDp) {
return (fDensity != 1.0f) ? fDensity * fDp : fDp;
}
public void setAdapter(ArrayList<Float> alPercentage) throws Exception {
this.alPercentage = alPercentage;
iDataSize = alPercentage.size();
float fSum = 0;
for (int i = 0; i < iDataSize; i++) {
fSum += alPercentage.get(i);
}
if (fSum != 100) {
Log.e(TAG, ERROR_NOT_EQUAL_TO_100);
iDataSize = 0;
throw new Exception(ERROR_NOT_EQUAL_TO_100);
}
}
<com.example.piecharts.PieChart
android:id="#+id/pieChart"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.example.piecharts.PieChart>

rotate and resize the image view with single finger in android

I am developing an app which has feature that resizing and rotating the imageview by dragging its bottom right corner button.
I saw one app which has feature that if we drag the bottom right corner button diagonally imageview size had resized or else if we drag the button left or right side direction imageview had rotated as per direction. I wish to implement this feature in my app
I am struggling to implement single finger rotation as well as resizing the imageview.
Please guide me in right way.
I am trying this code, and try to apply zoom and rotate but not able to do please help me.
belove code to do zoom and rotate finger base action.
public class ScaleActivity extends Activity {
ViewGroup lLayout;
static ImageView img, backgrndImg;
Canvas mCanvas;
float d;
private float mAspectQuotient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lLayout = (FrameLayout) findViewById(R.id.lLayout);
final CropView cv = new CropView(this);
lLayout.addView(cv);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class CropView extends ImageView {
private static final int SELECTION_RECT_PAINT_COLOR = 0xFF000000;
private static final int SELECTION_RECT_FILL_COLOR = 0x70FFFFFF;
private static final int TOUCH_TOLERANCE = 25;
private static final int xInc = 25;
private static final int yInc = 25;
Paint paint = new Paint();
private int initial_size = 200;
private Point leftTop, rightBottom, center, previous, currentPoint,
rectPos;
private Paint fillPaint;
private Paint rectPaint;
protected Rect selection, dest;
private boolean isAffectedBottom = false;
Bitmap bitmap, backgroundBitmap;
Rect rectf;
Rect knobRect;
private Context mContext;
int width, height;
private Matrix matrix = new Matrix();
Bitmap resizedBitmap;
// Adding parent class constructors
public CropView(Context context) {
super(context);
mContext = context;
backgroundBitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.toast_bkgrd);
bitmap = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.aviary_adjust_knob);
rectPaint = new Paint();
rectPaint.setStyle(Style.STROKE);
rectPaint.setColor(SELECTION_RECT_PAINT_COLOR);
fillPaint = new Paint();
fillPaint.setStyle(Style.FILL);
fillPaint.setColor(SELECTION_RECT_FILL_COLOR);
currentPoint = new Point(getWidth() / 2, getHeight() / 2);
width = backgroundBitmap.getWidth();
height = backgroundBitmap.getHeight();
initCropView();
}
public CropView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
initCropView();
}
public CropView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initCropView();
}
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas = canvas;
if (leftTop.equals(0, 0))
resetPoints();
mCanvas.save();
resizedBitmap = Bitmap.createBitmap(backgroundBitmap, 0, 0,
backgroundBitmap.getWidth(), backgroundBitmap.getHeight(),
matrix, true);
// mCanvas.drawBitmap(backgroundBitmap, matrix, rectPaint);
mCanvas.drawBitmap(resizedBitmap, null, selection, rectPaint);
mCanvas.drawBitmap(bitmap, selection.right - 25,
selection.bottom - 25, null);
rectPos.set(selection.left, selection.top);
mCanvas.restore();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
touchDown((int) event.getX(), (int) event.getY());
previous.set((int) event.getX(), (int) event.getY());
break;
case MotionEvent.ACTION_MOVE:
touchMove((int) event.getX(), (int) event.getY());
if (isActionInsideRectangle(event.getX(), event.getY())
&& !isAffectedBottom) {
drag((int) event.getX(), (int) event.getY());
invalidate(); // redraw rectangle
previous.set((int) event.getX(), (int) event.getY());
}
previous.set((int) event.getX(), (int) event.getY());
break;
case MotionEvent.ACTION_UP:
touchUp((int) event.getX(), (int) event.getY());
previous = new Point();
break;
}
return true;
}
private void initCropView() {
paint.setColor(Color.WHITE);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(5);
leftTop = new Point();
rightBottom = new Point();
center = new Point();
previous = new Point();
rectPos = new Point();
}
public void resetPoints() {
center.set(getWidth() / 2, getHeight() / 2);
leftTop.set((getWidth() - initial_size) / 2,
(getHeight() - initial_size) / 2);
rightBottom.set(leftTop.x + initial_size, leftTop.y + initial_size);
selection = new Rect(leftTop.x, leftTop.y, rightBottom.x,
rightBottom.y);
knobRect = new Rect(selection.right, selection.bottom,
bitmap.getWidth(), bitmap.getHeight());
dest = selection;
}
private boolean isActionInsideRectangle(float x, float y) {
int buffer = 10;
return (x >= (selection.left) && x <= (selection.right)
&& y >= (selection.top) && y <= (selection.bottom)) ? true
: false;
}
void touchDown(int x, int y) {
System.out.println("selection " + selection);
int dx = (previous.x - x) / 2;
int dy = (previous.y - y) / 2;
// d= rotation(dx,dy);
currentPoint.set(x, y);
if (pointsAreClose(x, y, selection.right, selection.bottom)) {
isAffectedBottom = true;
System.out.println("isAffectedBottom " + isAffectedBottom);
}
}
void touchMove(int x, int y) {
currentPoint.set(x, y);
if (isAffectedBottom) {
int dx = (previous.x - x) / 2;
int dy = (previous.y - y) / 2;
double startAngle = getAngle(previous.x, previous.y);
double currentAngle = getAngle(x, y);
matrix.postRotate((float) (startAngle - currentAngle),
selection.width() / 2.0f, selection.height() / 2.0f);
// selection.inset(dx, dy);
invalidate();
}
}
void touchUp(int x, int y) {
currentPoint.set(x, y);
isAffectedBottom = false;
}
private boolean pointsAreClose(float x1, float y1, float x2, float y2) {
return Math.hypot(x1 - x2, y1 - y2) < TOUCH_TOLERANCE;
}
private void drag(int x, int y) {
int movement;
movement = x - previous.x;
int movementY = y - previous.y;
selection.set(selection.left + movement, selection.top + movementY,
selection.right + movement, selection.bottom + movementY);
selection.sort();
invalidate();
}
/**
* Calculate the degree to be rotated by.
*
* #param event
* #return Degrees
*/
// private float rotation(float dx, float dy) {
//
// // double delta_x = (dx);
// // double delta_y = (dy);
// double radians = Math.atan2((selection.left) - (previous.y),
// (selection.top) - (previous.x));
// double radians2 = Math.atan2((selection.left) - (dy),
// (selection.top) - (dx));
//
// System.out.println("radians" + radians);
// System.out.println("" + radians2);
// System.out.println("radians2-radians" + (radians2 - radians));
// System.out.println(Math.toDegrees(radians2 - radians));
// return (float) Math.toDegrees(radians2 - radians);
//
// }
private double getAngle(double xTouch, double yTouch) {
double x = xTouch - (getWidth() / 2d);
double y = getHeight() - yTouch - (getHeight() / 2d);
switch (getQuadrant(x, y)) {
case 1:
System.out.println("1");
return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 2:
case 3:
System.out.println("32");
return 180 - (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
case 4:
System.out.println("4");
return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
default:
// ignore, does not happen
return 0;
}
}
/**
* #return The selected quadrant.
*/
private int getQuadrant(double x, double y) {
if (x >= 0) {
return y >= 0 ? 1 : 4;
} else {
return y >= 0 ? 2 : 3;
}
}
}
}
I have Design A Layout that may work as your need.
Download Demo here
Java File
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ClipArt extends RelativeLayout {
int baseh;
int basew;
int basex;
int basey;
ImageButton btndel;
ImageButton btnrot;
ImageButton btnscl;
RelativeLayout clip;
Context cntx;
boolean freeze = false;
int h;
int i;
ImageView image;
String imageUri;
boolean isShadow;
int iv;
RelativeLayout layBg;
RelativeLayout layGroup;
RelativeLayout.LayoutParams layoutParams;
public LayoutInflater mInflater;
int margl;
int margt;
float opacity = 1.0F;
Bitmap originalBitmap;
int pivx;
int pivy;
int pos;
Bitmap shadowBitmap;
float startDegree;
String[] v;
public ClipArt(Context paramContext) {
super(paramContext);
cntx = paramContext;
layGroup = this;
basex = 0;
basey = 0;
pivx = 0;
pivy = 0;
mInflater = ((LayoutInflater) paramContext.getSystemService("layout_inflater"));
mInflater.inflate(R.layout.clipart, this, true);
btndel = ((ImageButton) findViewById(R.id.del));
btnrot = ((ImageButton) findViewById(R.id.rotate));
btnscl = ((ImageButton) findViewById(R.id.sacle));
layoutParams = new RelativeLayout.LayoutParams(250, 250);
layGroup.setLayoutParams(layoutParams);
image = ((ImageView) findViewById(R.id.clipart));
image.setImageResource(R.drawable.ic_launcher);
setOnTouchListener(new View.OnTouchListener() {
final GestureDetector gestureDetector = new GestureDetector(ClipArt.this.cntx,
new GestureDetector.SimpleOnGestureListener() {
public boolean onDoubleTap(MotionEvent paramAnonymous2MotionEvent) {
return false;
}
});
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
layGroup.invalidate();
gestureDetector.onTouchEvent(event);
layGroup.performClick();
basex = ((int) (event.getRawX() - layoutParams.leftMargin));
basey = ((int) (event.getRawY() - layoutParams.topMargin));
break;
case MotionEvent.ACTION_MOVE:
int i = (int) event.getRawX();
int j = (int) event.getRawY();
layBg = ((RelativeLayout) getParent());
if ((i - basex > -(layGroup.getWidth() * 2 / 3))
&& (i - basex < layBg.getWidth() - layGroup.getWidth() / 3)) {
layoutParams.leftMargin = (i - basex);
}
if ((j - basey > -(layGroup.getHeight() * 2 / 3))
&& (j - basey < layBg.getHeight() - layGroup.getHeight() / 3)) {
layoutParams.topMargin = (j - basey);
}
layoutParams.rightMargin = -1000;
layoutParams.bottomMargin = -1000;
layGroup.setLayoutParams(layoutParams);
break;
}
return true;
}
return true;
}
});
this.btnscl.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint({ "NewApi" })
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
int j = (int) event.getRawX();
int i = (int) event.getRawY();
layoutParams = (RelativeLayout.LayoutParams) layGroup.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ClipArt.this.layGroup.invalidate();
ClipArt.this.basex = j;
ClipArt.this.basey = i;
ClipArt.this.basew = ClipArt.this.layGroup.getWidth();
ClipArt.this.baseh = ClipArt.this.layGroup.getHeight();
int[] loaction = new int[2];
layGroup.getLocationOnScreen(loaction);
margl = layoutParams.leftMargin;
margt = layoutParams.topMargin;
break;
case MotionEvent.ACTION_MOVE:
float f2 = (float) Math.toDegrees(Math.atan2(i - ClipArt.this.basey, j - ClipArt.this.basex));
float f1 = f2;
if (f2 < 0.0F) {
f1 = f2 + 360.0F;
}
j -= ClipArt.this.basex;
int k = i - ClipArt.this.basey;
i = (int) (Math.sqrt(j * j + k * k)
* Math.cos(Math.toRadians(f1 - ClipArt.this.layGroup.getRotation())));
j = (int) (Math.sqrt(i * i + k * k)
* Math.sin(Math.toRadians(f1 - ClipArt.this.layGroup.getRotation())));
k = i * 2 + ClipArt.this.basew;
int m = j * 2 + ClipArt.this.baseh;
if (k > 150) {
layoutParams.width = k;
layoutParams.leftMargin = (ClipArt.this.margl - i);
}
if (m > 150) {
layoutParams.height = m;
layoutParams.topMargin = (ClipArt.this.margt - j);
}
ClipArt.this.layGroup.setLayoutParams(layoutParams);
ClipArt.this.layGroup.performLongClick();
break;
}
return true;
}
return ClipArt.this.freeze;
}
});
this.btnrot.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint({ "NewApi" })
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
layoutParams = (RelativeLayout.LayoutParams) ClipArt.this.layGroup.getLayoutParams();
ClipArt.this.layBg = ((RelativeLayout) ClipArt.this.getParent());
int[] arrayOfInt = new int[2];
layBg.getLocationOnScreen(arrayOfInt);
int i = (int) event.getRawX() - arrayOfInt[0];
int j = (int) event.getRawY() - arrayOfInt[1];
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ClipArt.this.layGroup.invalidate();
ClipArt.this.startDegree = layGroup.getRotation();
ClipArt.this.pivx = (layoutParams.leftMargin + ClipArt.this.getWidth() / 2);
ClipArt.this.pivy = (layoutParams.topMargin + ClipArt.this.getHeight() / 2);
ClipArt.this.basex = (i - ClipArt.this.pivx);
ClipArt.this.basey = (ClipArt.this.pivy - j);
break;
case MotionEvent.ACTION_MOVE:
int k = ClipArt.this.pivx;
int m = ClipArt.this.pivy;
j = (int) (Math.toDegrees(Math.atan2(ClipArt.this.basey, ClipArt.this.basex))
- Math.toDegrees(Math.atan2(m - j, i - k)));
i = j;
if (j < 0) {
i = j + 360;
}
ClipArt.this.layGroup.setRotation((ClipArt.this.startDegree + i) % 360.0F);
break;
}
return true;
}
return ClipArt.this.freeze;
}
});
this.btndel.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
if (!ClipArt.this.freeze) {
layBg = ((RelativeLayout) ClipArt.this.getParent());
layBg.performClick();
layBg.removeView(ClipArt.this.layGroup);
}
}
});
}
public void disableAll() {
this.btndel.setVisibility(4);
this.btnrot.setVisibility(4);
this.btnscl.setVisibility(4);
}
public ImageView getImageView() {
return this.image;
}
public void setFreeze(boolean paramBoolean) {
this.freeze = paramBoolean;
}
}
Layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<ImageButton android:id="#+id/rotate" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/rotation"/>
<ImageButton android:id="#+id/sacle" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/pointer"/>
<ImageButton android:id="#+id/del" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/close"/>
<ImageView android:id="#+id/clipart" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"/>
</RelativeLayout>
and images put in drawable
please check the repository in github i create it .
count the distance from center point in the rotate and zoom view to the push point.
just use :
private float getDistance(Point a, Point b) {
float v = ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y));
return ((int) (Math.sqrt(v) * 100)) / 100f;
}
and count the OA/OB that value can count the view new height and width
count the angle AOB, the A is the first push point , the B is the last move point ,the O is the center of the View Point .
and then just set new height and width for view ,and count the left and top for view .
souce link : https://github.com/ryanch741/android-view-rotate-zoom-single-finger
the code:
Point pushPoint;
int lastImgWidth;
int lastImgHeight;
int lastImgLeft;
int lastImgTop;
int lastImgAngle;
double lastComAngle;
int pushImgWidth;
int pushImgHeight;
int lastPushBtnLeft;
int lastPushBtnTop;
private View mView;
private Point mViewCenter;
private static final double PI = 3.14159265359;
public PushBtnTouchListener(View mView) {
this.mView = mView;
}
private FrameLayout.LayoutParams pushBtnLP;
private FrameLayout.LayoutParams imgLP;
float lastX = -1;
float lastY = -1;
#Override
public boolean onTouch(View pushView, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
// 主点按下
case MotionEvent.ACTION_DOWN:
pushBtnLP = (FrameLayout.LayoutParams) pushView.getLayoutParams();
imgLP = (FrameLayout.LayoutParams) mView.getLayoutParams();
pushPoint = getPushPoint(pushBtnLP, event);
lastImgWidth = imgLP.width;
lastImgHeight = imgLP.height;
lastImgLeft = imgLP.leftMargin;
lastImgTop = imgLP.topMargin;
lastImgAngle = (int) mView.getRotation();
lastPushBtnLeft = pushBtnLP.leftMargin;
lastPushBtnTop = pushBtnLP.topMargin;
pushImgWidth = pushBtnLP.width;
pushImgHeight = pushBtnLP.height;
lastX = event.getRawX();
lastY = event.getRawY();
refreshImageCenter();
break;
// 副点按下
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_UP: {
break;
}
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
float rawX = event.getRawX();
float rawY = event.getRawY();
if (lastX != -1) {
if (Math.abs(rawX - lastX) < 5 && Math.abs(rawY - lastY) < 5) {
return false;
}
}
lastX = rawX;
lastY = rawY;
Point O = mViewCenter, A = pushPoint, B = getPushPoint(pushBtnLP, event);
float dOA = getDistance(O, A);
float dOB = getDistance(O, B);
float f = dOB / dOA;
int newWidth = (int) (lastImgWidth * f);
int newHeight = (int) (lastImgHeight * f);
imgLP.leftMargin = lastImgLeft - ((newWidth - lastImgWidth) / 2);
imgLP.topMargin = lastImgTop - ((newHeight - lastImgHeight) / 2);
imgLP.width = newWidth;
imgLP.height = newHeight;
mView.setLayoutParams(imgLP);
float fz = (((A.x - O.x) * (B.x - O.x)) + ((A.y - O.y) * (B.y - O.y)));
float fm = dOA * dOB;
double comAngle = (180 * Math.acos(fz / fm) / PI);
if (Double.isNaN(comAngle)) {
comAngle = (lastComAngle < 90 || lastComAngle > 270) ? 0 : 180;
} else if ((B.y - O.y) * (A.x - O.x) < (A.y - O.y) * (B.x - O.x)) {
comAngle = 360 - comAngle;
}
lastComAngle = comAngle;
float angle = (float) (lastImgAngle + comAngle);
angle = angle % 360;
mView.setRotation(angle);
Point imageRB = new Point(mView.getLeft() + mView.getWidth(), mView.getTop() + mView.getHeight());
Point anglePoint = getAnglePoint(O, imageRB, angle);
pushBtnLP.leftMargin = (int) (anglePoint.x - pushImgWidth / 2);
pushBtnLP.topMargin = (int) (anglePoint.y - pushImgHeight / 2);
pushView.setLayoutParams(pushBtnLP);
break;
}
return false;
}
private void refreshImageCenter() {
int x = mView.getLeft() + mView.getWidth() / 2;
int y = mView.getTop() + mView.getHeight() / 2;
mViewCenter = new Point(x, y);
}
private Point getPushPoint(FrameLayout.LayoutParams lp, MotionEvent event) {
return new Point(lp.leftMargin + (int) event.getX(), lp.topMargin + (int) event.getY());
}
private float getDistance(Point a, Point b) {
float v = ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y));
return ((int) (Math.sqrt(v) * 100)) / 100f;
}
private Point getAnglePoint(Point O, Point A, float angle) {
int x, y;
float dOA = getDistance(O, A);
double p1 = angle * PI / 180f;
double p2 = Math.acos((A.x - O.x) / dOA);
x = (int) (O.x + dOA * Math.cos(p1 + p2));
double p3 = Math.acos((A.x - O.x) / dOA);
y = (int) (O.y + dOA * Math.sin(p1 + p3));
return new Point(x, y);
}
I'm assuming the rotation/scaling happens from the image center? In that case, it's simple trigonometry to find the rotation angle and the size:
Calculate dx and dy of the finger's coordinates minus the center coordinates. Math.atan2(dy, dx) is the rotation angle (in radians) and Math.hypot(dx,dy) can be used for the relative size, or just double the dx/dy and use directly.

Is it possible to remove transparent pixels from bitmap in android

In my application i am taking screenshot if the image doesn't fill imageView then transparent pixels are added to bitmap.Is it possible to remove transparent pixels from bitmap or take screenshot without transparent pixels.Thanks in advance.
This method is a lot faster:
static Bitmap trim(Bitmap source) {
int firstX = 0, firstY = 0;
int lastX = source.getWidth();
int lastY = source.getHeight();
int[] pixels = new int[source.getWidth() * source.getHeight()];
source.getPixels(pixels, 0, source.getWidth(), 0, 0, source.getWidth(), source.getHeight());
loop:
for (int x = 0; x < source.getWidth(); x++) {
for (int y = 0; y < source.getHeight(); y++) {
if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
firstX = x;
break loop;
}
}
}
loop:
for (int y = 0; y < source.getHeight(); y++) {
for (int x = firstX; x < source.getWidth(); x++) {
if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
firstY = y;
break loop;
}
}
}
loop:
for (int x = source.getWidth() - 1; x >= firstX; x--) {
for (int y = source.getHeight() - 1; y >= firstY; y--) {
if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
lastX = x;
break loop;
}
}
}
loop:
for (int y = source.getHeight() - 1; y >= firstY; y--) {
for (int x = source.getWidth() - 1; x >= firstX; x--) {
if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
lastY = y;
break loop;
}
}
}
return Bitmap.createBitmap(source, firstX, firstY, lastX - firstX, lastY - firstY);
}
I have done this way and it works great.
public static Bitmap createTrimmedBitmap(Bitmap bmp) {
int imgHeight = bmp.getHeight();
int imgWidth = bmp.getWidth();
int smallX=0,largeX=imgWidth,smallY=0,largeY=imgHeight;
int left=imgWidth,right=imgWidth,top=imgHeight,bottom=imgHeight;
for(int i=0;i<imgWidth;i++)
{
for(int j=0;j<imgHeight;j++)
{
if(bmp.getPixel(i, j) != Color.TRANSPARENT){
if((i-smallX)<left){
left=(i-smallX);
}
if((largeX-i)<right)
{
right=(largeX-i);
}
if((j-smallY)<top)
{
top=(j-smallY);
}
if((largeY-j)<bottom)
{
bottom=(largeY-j);
}
}
}
}
Log.d(TAG, "left:" + left + " right:" + right + " top:" + top + " bottom:" + bottom);
bmp=Bitmap.createBitmap(bmp,left,top,imgWidth-left-right, imgHeight-top-bottom);
return bmp;
}
Bitmap imageWithBG = Bitmap.createBitmap(image.getWidth(), image.getHeight(),image.getConfig()); // Create another image the same size
imageWithBG.eraseColor(Color.WHITE); // set its background to white, or whatever color you want
Canvas canvas = new Canvas(imageWithBG); // create a canvas to draw on the new image
canvas.drawBitmap(image, 0f, 0f, null); // draw old image on the background
image.recycle(); // clear out old image
To trim crop transparent borders of a image in Android you ca use
this arrange. Work faster because don't need read all pixels, it just slice the bitmap, more details: CropTrimTransparentImage
public Bitmap crop (Bitmap bitmap){
int height = bitmap.getHeight();
int width = bitmap.getWidth();
int[] empty = new int[width];
int[] buffer = new int[width];
Arrays.fill(empty,0);
int top = 0;
int left = 0;
int botton = height;
int right = width;
for (int y = 0; y < height; y++) {
bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
if (!Arrays.equals(empty, buffer)) {
top = y;
break;
}
}
for (int y = height - 1; y > top; y--) {
bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
if (!Arrays.equals(empty, buffer)) {
botton = y;
break;
}
}
int bufferSize = botton -top +1;
empty = new int[bufferSize];
buffer = new int[bufferSize];
Arrays.fill(empty,0);
for (int x = 0; x < width; x++) {
bitmap.getPixels(buffer, 0, 1, x, top + 1, 1, bufferSize);
if (!Arrays.equals(empty, buffer)) {
left = x;
break;
}
}
for (int x = width - 1; x > left; x--) {
bitmap.getPixels(buffer, 0, 1, x, top + 1, 1, bufferSize);
if (!Arrays.equals(empty, buffer)) {
right = x;
break;
}
}
Bitmap cropedBitmap = Bitmap.createBitmap(bitmap, left, top, right-left, botton-top);
return cropedBitmap;
}

Android Bitmap is black

I'm trying to draw a map from a textfile onto a Bitmap, but the Bitmap is all black
First i load a textfile that looks like this (shortened):
0000000000 (200 width)
0111111110
0111100010
0000111110
0000111000
0000000000
(120 height)
Where "1" is ground and "0" is a wall, 1 should be white and 0 should be black.
Code:
public Map(String map) {
this.map = map;
init();
}
public void init() {
mapArray = new int[WIDTH*HEIGHT];
String[] splitMap = map.split("\n");
int width = splitMap[0].length();
int height = splitMap.length;
int[] colors = new int[WIDTH * HEIGHT];
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
int type = Integer.valueOf(splitMap[y].charAt(x));
setType(x, y, type);
if(type == WALL) {
setColor(x, y, Color.rgb(0, 0, 0), colors);
} else if(type == GROUND) {
setColor(x, y, Color.rgb(255, 255, 255), colors);
} else if(type == GOAL) {
setColor(x, y, Color.rgb(255, 255, 255), colors);
}
}
}
bitmap = Bitmap.createBitmap(colors, WIDTH, HEIGHT, Config.ARGB_8888);
}
public void setColor(int x, int y, int color, int[] colors) {
for(int y1 = 0; y1 < 4; y1++) {
for(int x1 = 0; x1 < 4; x1++) {
colors[(x + x1) + (y + y1) * WIDTH] = color;
}
}
}
public void setPixel(int x, int y, int color) {
for(int y1 = 0; y1 < 4; y1++) {
for(int x1 = 0; x1 < 4; x1++) {
bitmap.setPixel(x + x1, y + y1, color);
}
}
}
public void setType(int x, int y, int type) {
for(int y1 = 0; y1 < 4; y1++) {
for(int x1 = 0; x1 < 4; x1++) {
mapArray[(x + x1) + (y + y1) * WIDTH] = type;
}
}
}
public int getType(int x, int y) {
return mapArray[x + y * WIDTH];
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
}
private final static int WALL = 0;
private final static int GROUND = 1;
private final static int GOAL = 2;
private final static int WIDTH = 800;
private final static int HEIGHT = 480;
private int[] mapArray = null;
private String map = null;
public Bitmap bitmap;
int type = Integer.valueOf(splitMap[y].charAt(x));
That's the line that's causing the problem.
scala> Integer.valueOf('1')
res3: java.lang.Integer = 49
scala> Integer.valueOf('0')
res4: java.lang.Integer = 48
The problem is that charAt gives you a char, which you then convert into an integer. What you really want to do is Integer.parseInt(splitMap[y].substring(x,x+1)
Integer.valueOf("0".substring(0,1))
res7: java.lang.Integer = 0
This illustrates a lesson though - never leave a switch statement without providing a default; similarly never leave an if/else if/... without leaving an else. Even if you're expecting never to hit it, you should put some noticeable error message if you do; it will help you debug.

Categories

Resources