How keep previous draw on same canvas? - android

I am able to draw a text on canvas on motion view now the problem is that when i draw text & go for the next draw on same canvas my draw text is getting disappear i mean screen is getting redraw because of invalidate i want keep my previous draw and make new draw on same canvas how am i going to do that ?
public class PuzzleView extends View {
private float width; // width of one tile
private float height; // height of one tile
private int selX; // X index of selection
private int selY; // Y index of selection
private final Rect selRect = new Rect();
private final Game game;
float positionX = 5;
float positionY = 15;
String strgettile = null;
float x, y;
Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
String getorientation;
public PuzzleView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w / 9f;
height = h / 9f;
// getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
// canvas.save();
// Draw the background...
Paint background = new Paint();
background.setColor(getResources().getColor(R.color.puzzle_background));
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
// Draw the board...
// Define colors for the grid lines
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.puzzle_dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.puzzle_hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.puzzle_light));
// Draw the minor grid lines
for (int i = 0; i < 9; i++) {
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
}
// Draw the major grid lines
for (int i = 0; i < 9; i++) {
if (i % 3 != 0)
continue;
canvas.drawLine(0, i * height, getWidth(), i * height, dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
}
// // Draw the numbers...
Paint hint = new Paint();
int m;
if (strgettile != null) {
for (m = 0; m < strgettile.length(); m++) {
System.out.println(strgettile.charAt(m));
char convertst = strgettile.charAt(m);
String characterToString = Character.toString(convertst);
if (getorientation.equalsIgnoreCase("Horizontal")) {
canvas.drawText(characterToString, m * width + positionX,
positionY, foreground); // for motion event
hint.setColor(Color.BLACK);
hint.setTextSize(45);
} else {
canvas.drawText(characterToString, positionX, m * height
+ positionY, foreground);
hint.setColor(Color.BLACK);
hint.setTextSize(45);
}
}
//invalidate();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN)
return super.onTouchEvent(event);
// select((int) (event.getX() / width), (int) (event.getY() /
// height));
game.showKeypadOrError(selX, selY);
foreground.setColor(getResources().getColor(R.color.puzzle_foreground));
foreground.setStyle(Style.FILL);
foreground.setTextSize(height * 0.75f);
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
// // Draw the number in the center of the tile
FontMetrics fm = foreground.getFontMetrics();
// // Centering in X: use alignment (and X at midpoint)
// positionX = width / 2;
// // Centering in Y: measure ascent/descent first
// positionY = height / 2 - (fm.ascent + fm.descent) / 2;
positionX = (int) event.getX();
positionY = (int) event.getY() - (fm.ascent + fm.descent) / 2;
// Draw the numbers...
// Define color and style for numbers
// invalidate();
Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY);
return true;
}
public void setSelectedTile(String tile, String strorientations) {
// TODO Auto-generated method stub
Log.v("getting string in puzzle view ", tile);
strgettile = tile;
getorientation = strorientations;
invalidate();
}
}

Call invalidate() at the end of onDraw.
This function let the onDraw to get called again.

Related

Convert sinusoid values to audio in android

I am graphically representing audio on x and y axis. From those y-axis points I want to generate audio again.
Followed https://github.com/billthefarmer/scope this to get points on y-axis. I have all of the values of y-axis points. These points can be used to represent a wave graphically.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Locale;
// Scope
public class Scope extends View {
private int width;
private int height;
private Path path;
private Canvas cb;
private Paint paint;
private Bitmap bitmap;
private Bitmap graticule;
protected boolean storage;
protected boolean clear;
protected float step;
protected float scale;
protected float start;
protected float index;
protected float yscale;
protected boolean points;
protected MainActivity.Audio audio;
// Scope
public Scope(Context context, AttributeSet attrs) {
super(context, attrs);
// Create path and paint
path = new Path();
paint = new Paint();
}
// On size changed
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Get dimensions
width = w;
height = h;
// Create a bitmap for trace storage
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
cb = new Canvas(bitmap);
// Create a bitmap for the graticule
graticule = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(graticule);
// Black background
canvas.drawColor(Color.BLACK);
// Set up paint
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.argb(255, 0, 63, 0));
// Draw graticule
for (int i = 0; i < width; i += MainActivity.SIZE)
canvas.drawLine(i, 0, i, height, paint);
canvas.translate(0, height / 2);
for (int i = 0; i < height / 2; i += MainActivity.SIZE) {
canvas.drawLine(0, i, width, i, paint);
canvas.drawLine(0, -i, width, -i, paint);
}
// Draw the graticule on the bitmap
cb.drawBitmap(graticule, 0, 0, null);
cb.translate(0, height / 2);
}
private int max;
// On draw
#Override
protected void onDraw(Canvas canvas) {
// Check for data
if ((audio == null) || (audio.data == null)) {
canvas.drawBitmap(graticule, 0, 0, null);
return;
}
// Draw the graticule on the bitmap
if (!storage || clear) {
cb.drawBitmap(graticule, 0, -height / 2, null);
clear = false;
}
// Calculate x scale etc
float xscale = (float) (2.0 / ((audio.sample / 100000.0) * scale));
int xstart = Math.round(start);
int xstep = Math.round((float) 1.0 / xscale);
int xstop = Math.round(xstart + ((float) width / xscale));
if (xstop > audio.length)
xstop = (int) audio.length;
// Calculate y scale
if (max < 4096)
max = 4096;
yscale = (float) (max / (height / 2.0));
max = 0;
// Draw the trace
path.rewind();
path.moveTo(0, 0);
if (xscale < 1.0) {
for (int i = 0; i < xstop - xstart; i += xstep) {
if (max < Math.abs(audio.data[i + xstart]))
max = Math.abs(audio.data[i + xstart]);
float x = (float) i * xscale;
float y = -(float) audio.data[i + xstart] / yscale;
path.lineTo(x, y);
Log.d("y values", "y = " + String.valueOf(y)); // KING
writeToFile("y = " + String.valueOf(y), getContext());
}
} else {
for (int i = 0; i < xstop - xstart; i++) {
if (max < Math.abs(audio.data[i + xstart]))
max = Math.abs(audio.data[i + xstart]);
float x = (float) i * xscale;
float y = -(float) audio.data[i + xstart] / yscale;
path.lineTo(x, y);
Log.d("y values", "y = " + String.valueOf(y)); // KING
writeToFile("y = " + String.valueOf(y), getContext());
// Draw points at max resolution
if (points) {
path.addRect(x - 2, y - 2, x + 2, y + 2, Path.Direction.CW);
path.moveTo(x, y);
Log.d("y values", "y = " + String.valueOf(y)); // KING
writeToFile("y = " + String.valueOf(y), getContext());
}
}
}
// Green trace
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
cb.drawPath(path, paint);
// Draw index
if (index > 0 && index < width) {
// Yellow index
paint.setColor(Color.YELLOW);
paint.setAntiAlias(false);
cb.drawLine(index, -height / 2, index, height / 2, paint);
paint.setAntiAlias(true);
paint.setTextSize(height / 48);
paint.setTextAlign(Paint.Align.LEFT);
// Get value
int i = Math.round(index / xscale);
if (i + xstart < audio.length) {
float y = -audio.data[i + xstart] / yscale;
// Draw value
String s = String.format(Locale.getDefault(), "%3.2f",
audio.data[i + xstart] / 32768.0);
cb.drawText(s, index, y, paint);
}
paint.setTextAlign(Paint.Align.CENTER);
// Draw time value
if (scale < 100.0) {
String s = String.format(Locale.getDefault(),
(scale < 1.0) ? "%3.3f" :
(scale < 10.0) ? "%3.2f" : "%3.1f",
(start + (index * scale)) /
MainActivity.SMALL_SCALE);
cb.drawText(s, index, height / 2, paint);
// Log.d("y values", "y = " + String.valueOf(y));
} else {
String s = String.format(Locale.getDefault(), "%3.3f",
(start + (index * scale)) /
MainActivity.LARGE_SCALE);
cb.drawText(s, index, height / 2, paint);
}
}
canvas.drawBitmap(bitmap, 0, 0, null);
}
private void writeToFile(String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("Sinusoids.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
// On touch event
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
// Set the index from the touch dimension
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
index = x;
break;
case MotionEvent.ACTION_MOVE:
index = x;
break;
case MotionEvent.ACTION_UP:
index = x;
break;
}
return true;
}
}
Generate byte array from y-axis points. The array can then be converted to sound.

Paint stroke not covering all the side in android

Hi i am creating indicator for doughnut chart but it is covering only three side. Here i added onDraw method.The selected chart index arc should be highlighted with indicator.The indicator should be cover all the four sides.
Code:
#Override
public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) {
paint.setAntiAlias(true);
paint.setStyle(Style.FILL);
int legendSize = getLegendSize(mRenderer, height / 5, 0);
int left = x;
int top = y;
int right = x + width;
int sLength = mDataset.getItemCount();
double total = 0;
String[] titles = new String[sLength];
for (int i = 0; i < sLength; i++) {
total += mDataset.getValue(i);
titles[i] = mDataset.getCategory(i);
}
if (mRenderer.isFitLegend()) {
legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, paint, true);
}
int bottom = y + height - legendSize;
drawBackground(mRenderer, canvas, x, y, width, height, paint, false, Renderer.NO_COLOR);
float currentAngle = mRenderer.getStartAngle();
float labelCurrentAngle = mRenderer.getStartAngle();
// int mRadius = Math.min(Math.abs(right - left), Math.abs(bottom - top));
// int radius = (int) (500 * 0.35) + 50;
//Log.i("radius++", "" + radius);
int mRadius = Math.min(Math.abs(right - left), Math.abs(bottom - top));
double rCoef = 0.35 * mRenderer.getScale();
double decCoef = 0.2 / sLength;
int radius = (int) (mRadius * rCoef);
if (mCenterX == 0) {
mCenterX = (left + right) / 2;
}
if (mCenterY == 0) {
mCenterY = (bottom + top) / 2;
}
// Hook in clip detection after center has been calculated
mPieMap.setDimensions(radius, mCenterX, mCenterY);
boolean loadPieCfg = !mPieMap.areAllSegmentPresent(sLength);
if (loadPieCfg) {
mPieMap.clearPieSegments();
}
float shortRadius = radius * 0.9f;
float longRadius = radius * 1.1f;
RectF oval = new RectF(mCenterX - radius, mCenterY - radius, mCenterX + radius, mCenterY + radius);
for (int i = 0; i < sLength; i++) {
float value = (float) mDataset.getValue(i);
float angle = (float) (value / total * 360);
int color = mRenderer.getRenderers().get(i).getColor();
if (mRenderer.getRenderers().get(i).isClicked()) {
ClickedArc.CANVAS = canvas;
ClickedArc.CURRENT_ANGLE = currentAngle;
ClickedArc.ANGLE = angle;
ClickedArc.COLOR = color;
ClickedArc.INDEX = mRenderer.getRenderers().get(i).getDataIndex();
} else {
Paint paint3 = new Paint(Paint.ANTI_ALIAS_FLAG);
paint3.setStrokeCap(Paint.Cap.ROUND);
paint3.setStyle(Style.FILL);
int[] colors = {color, color};
RadialGradient gradient3 = new RadialGradient(mCenterX, mCenterY, radius, colors, null, android.graphics.Shader.TileMode.CLAMP);
paint3.setShader(gradient3);
paint3.setAntiAlias(true);
canvas.drawArc(oval, currentAngle, angle, true, paint3);
}
try {
if (mRenderer.getRenderers().get(ClickedArc.INDEX).isClicked()) {
Paint paint3 = new Paint(Paint.ANTI_ALIAS_FLAG);
paint3.setStyle(Style.FILL);
paint3.setColor(Color.WHITE);
Paint shadow = new Paint(Paint.ANTI_ALIAS_FLAG);
int[] colors = {Color.BLACK, Color.BLACK};
RadialGradient gradient3 = new RadialGradient(mCenterX, mCenterY, radius, colors, null, android.graphics.Shader.TileMode.CLAMP);
shadow.setShader(gradient3);
shadow.setAntiAlias(true);
shadow.setColor(Color.BLACK);
shadow.setStrokeWidth(8);
shadow.setDither(true);
shadow.setStyle(Paint.Style.STROKE);
shadow.setStrokeCap(Paint.Cap.BUTT);
shadow.setAntiAlias(true);
int shadowRadius = radius + 2;
RectF shadowOval = new RectF(mCenterX - shadowRadius, mCenterY - shadowRadius, mCenterX + shadowRadius, mCenterY + shadowRadius);
canvas.drawArc(shadowOval, ClickedArc.CURRENT_ANGLE - 1, ClickedArc.ANGLE + 2, true, shadow);
canvas.drawArc(oval, ClickedArc.CURRENT_ANGLE, ClickedArc.ANGLE, true, paint3);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
if (loadPieCfg) {
mRenderer.getRenderers().get(i).setDataIndex(i);
mPieMap.addPieSegment(i, value, currentAngle, angle + currentAngle);
}
currentAngle += angle;
}
radius -= (int) mRadius * decCoef;
shortRadius -= mRadius * decCoef - 2;
List<RectF> prevLabelsBounds = new ArrayList<RectF>();
for (int i = 0; i < sLength; i++) {
float value = (float) mDataset.getValue(i);
float angle = (float) (value / total * 360);
drawLabel(canvas, mDataset.getCategory(i), mRenderer, prevLabelsBounds, mCenterX, mCenterY, shortRadius / 2 + 50, longRadius / 2 + 50,
labelCurrentAngle, angle, left, right, mRenderer.getLabelsColor(), paint, true, mRenderer.getRenderers().get(i));
Point sPoint = mRenderer.getRenderers().get(i).getCenterPoint();
Point ePoint = new Point((int) mRenderer.getRenderers().get(i).getTextWidth(), (int) mRenderer.getRenderers().get(i).getTextHeight());
mPieMap.addLabelSegment(i, value, sPoint, ePoint);
labelCurrentAngle += angle;
}
prevLabelsBounds.clear();
}

How to set text characters in cubes horizontally and vertically both

I am making crossword app i want to set my text horizontal & vertical both now its coming in cross align i want to make it vertical android another text to vertical
public class PuzzleView extends View {
private float width; // width of one tile
private float height; // height of one tile
private int selX; // X index of selection
private int selY; // Y index of selection
private final Rect selRect = new Rect();
private final Game game;
public PuzzleView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w / 9f;
height = h / 9f;
getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
// Draw the background...
Paint background = new Paint();
background.setColor(getResources().getColor(R.color.puzzle_background));
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
// Draw the board...
// Define colors for the grid lines
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.puzzle_dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.puzzle_hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.puzzle_light));
// Draw the minor grid lines
for (int i = 0; i < 9; i++) {
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
}
// Draw the major grid lines
for (int i = 0; i < 9; i++) {
if (i % 3 != 0)
continue;
canvas.drawLine(0, i * height, getWidth(), i * height, dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
}
// Draw the numbers...
// Define color and style for numbers
Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
foreground.setColor(getResources().getColor(R.color.puzzle_foreground));
foreground.setStyle(Style.FILL);
foreground.setTextSize(height * 0.75f);
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
// // Draw the number in the center of the tile
FontMetrics fm = foreground.getFontMetrics();
// // Centering in X: use alignment (and X at midpoint)
float x = width / 2;
// // Centering in Y: measure ascent/descent first
float y = height / 2 - (fm.ascent + fm.descent) / 2;
Paint hint = new Paint();
String str = "TEXT";
int m;
for (m = 0; m < str.length(); m++) {
System.out.println(str.charAt(m));
char convertst = str.charAt(m);
String characterToString = Character.toString(convertst);
//canvas.drawText(characterToString, x, y, hint);
canvas.drawText(characterToString, m
* width + x, m * height + y, foreground); //its working in cross
hint.setColor(Color.BLACK);
hint.setTextSize(45);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN)
return super.onTouchEvent(event);
select((int) (event.getX() / width), (int) (event.getY() / height));
game.showKeypadOrError(selX, selY);
Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(TAG, "onKeyDown: keycode=" + keyCode + ", event=" + event);
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
select(selX, selY - 1);
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
select(selX, selY + 1);
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
select(selX - 1, selY);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
select(selX + 1, selY);
break;
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_SPACE:
setSelectedTile(0);
break;
case KeyEvent.KEYCODE_1:
setSelectedTile(1);
break;
case KeyEvent.KEYCODE_2:
setSelectedTile(2);
break;
case KeyEvent.KEYCODE_3:
setSelectedTile(3);
break;
case KeyEvent.KEYCODE_4:
setSelectedTile(4);
break;
case KeyEvent.KEYCODE_5:
setSelectedTile(5);
break;
case KeyEvent.KEYCODE_6:
setSelectedTile(6);
break;
case KeyEvent.KEYCODE_7:
setSelectedTile(7);
break;
case KeyEvent.KEYCODE_8:
setSelectedTile(8);
break;
case KeyEvent.KEYCODE_9:
setSelectedTile(9);
break;
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
game.showKeypadOrError(selX, selY);
break;
default:
return super.onKeyDown(keyCode, event);
}
return true;
}
public void setSelectedTile(int tile) {
if (game.setTileIfValid(selX, selY, tile)) {
invalidate();// may change hints
} else {
// Number is not valid for this tile
Log.d(TAG, "setSelectedTile: invalid: " + tile);
startAnimation(AnimationUtils.loadAnimation(game, R.anim.shake));
}
}
private void select(int x, int y) {
invalidate(selRect);
selX = Math.min(Math.max(x, 0), 8);
selY = Math.min(Math.max(y, 0), 8);
getRect(selX, selY, selRect);
invalidate(selRect);
}
private void getRect(int x, int y, Rect rect) {
rect.set((int) (x * width), (int) (y * height),
(int) (x * width + width), (int) (y * height + height));
}
}
///////////////////////////////////////////////////
some part of the code enter code here
width = w / 9f;
height = h / 9f;
float x = width / 2;
// // Centering in Y: measure ascent/descent first
float y = height / 2 - (fm.ascent + fm.descent) / 2;
/// This is the main area where i am handling the position /////
String str = "TEXT";
int m;
for (m = 0; m < str.length(); m++) {
System.out.println(str.charAt(m));
char convertst = str.charAt(m);
String characterToString = Character.toString(convertst);
canvas.drawText(characterToString, m
* width + x, m * height + y, foreground); //its working in cross
hint.setColor(Color.BLACK);
hint.setTextSize(45);
}
here is the view i am getting:
Here is the view i which i want :
Do not increase start parameter.
canvas.drawText(characterToString, x, m * height + y, foreground);

How to draw a pie chart using RectF which will be easy to support multiple screen size in android?

Hi I am using following code to draw a pie chart in android :-
public class Chart extends View
{
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float[] value_degree;
private String[] Title_value;
RectF rectf = new RectF(50, 5, 200, 150);
Rect rect = new Rect(50, 5, 200, 150);
float temp = 0;
public Chart(Context context, float[] values, String[] heading)
{
super(context);
value_degree = new float[values.length];
Title_value = new String[heading.length];
for (int i = 0; i < values.length; i++)
{
value_degree[i] = values[i];
Log.i("abc", "" + values[i]);
Title_value[i] = heading[i];
}
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Random r;
int centerX = (rect.left + rect.right) / 2;
int centerY = (rect.top + rect.bottom) / 2;
int radius = (rect.right - rect.left) / 2;
int color;
radius *= 0.5; // 1 will put the text in the border, 0 will put the text
// in the center. Play with this to set the distance of
// your text.
for (int i = 0; i < value_degree.length; i++)
{
if (i == 0)
{
r = new Random();
color = Color.argb(100, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
Log.i("Color", "" + color);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
paint.setColor(Color.BLACK); // set this to the text color.
paint.setTextSize(12);
/*
* paint.setTextAlign(Align.CENTER);
*/float medianAngle = (temp + (value_degree[i] / 2f))
* (float) Math.PI / 180f; // this angle will place the
// text in the center of the
// arc.
canvas.drawText(Title_value[i],
(float) (centerX + (radius * Math.cos(medianAngle))),
(float) (centerY + (radius * Math.sin(medianAngle))),
paint);
} else
{
temp += value_degree[i - 1];
r = new Random();
color = Color.argb(255, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
Log.i("Else Color", "" + color);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
paint.setColor(Color.BLACK); // set this to the text color.
paint.setTextSize(12);
/*
* paint.setTextAlign(Align.CENTER);
*/float medianAngle = (temp + (value_degree[i] / 2f))
* (float) Math.PI / 180f; // this angle will place the
// text in the center of the
// arc.
canvas.drawText(Title_value[i],
(float) (centerX + (radius * Math.cos(medianAngle))),
(float) (centerY + (radius * Math.sin(medianAngle))),
paint);
}
}
}
}
It is showing chart in good quality in small screen sizes. But when I check it on big screen like S4 or other same screen size device it is shows a pie chart in very small size.
What should I do so it will draw perfectly on small as well as big screens?
Please help me, suggest something.
Also suggest how can I take color value to each slice in pie chart as it is assigned randomly.

Sudoku crashes when game starts

Hi I am a beginner to android and I am doing a basic sudoku application to study android and finds myself stuck when i start the game..APP CRASH..!!!!
Whenever I try to start the game it crashes and takes me back to the menu screen in my emulator.Someone please help me on this..
Thanks in advance.
The following is my code:
puzzleview.java
package org.example.sudoku;
public class puzzleview extends View {
private static final String TAG="SUDOKU";
private float width;
private float height;
private int selX;
private int selY;
private final Rect selRect= new Rect();
private final Game game;
public puzzleview(Context context){
super(context);
this.game=(Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
}
#Override
protected void onSizeChanged(int w,int h,int oldh,int oldw){
width = w/9f;
height = h/9f;
getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged width " + width +", height "+ height);
super.onSizeChanged(w, h, oldw, oldh);
}
private void getRect(int selX2, int selY2, Rect selRect2) {
// TODO Auto-generated method stub
}
#Override
protected void onDraw(Canvas canvas){
Paint background=new Paint();
background.setColor(getResources().getColor(R.color.puzzle_background));
canvas.drawRect(0,0, getWidth(), getHeight(), background);
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.puzzle_dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.puzzle_hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.puzzle_light));
for (int i = 0; i < 9; i++) {
canvas.drawLine(0, i * height, getWidth(), i * height,
light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(),
light);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
for(int i=0; i<9; i++){
if(i%3!=0)
continue;
canvas.drawLine(0,i*height,getWidth(),i*height,dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
foreground.setColor(getResources().getColor(R.color.puzzle_foreground));
foreground.setStyle(Style.FILL);
foreground.setTextSize (height * 0.75f);
foreground.setTextScaleX(width/height);
foreground.setTextAlign(Paint.Align.CENTER);
FontMetrics fm=foreground.getFontMetrics();
float x=width/2;
float y=height/2 - (fm.ascent+fm.descent)/2;
for(int i=0;i<9;i++){
for(int j = 0;j<9;j++){
Line 95 ---->: canvas.drawText(this.game.getTileString(i, j), i
* width + x, j * height + y, foreground);
}
}
}
}
logcat:
06-09 10:51:30.163: E/AndroidRuntime(2266): at org.example.sudoku.puzzleview.onDraw(puzzleview.java:95)
It depends how you are using your view, but if you are using it in XML then you need to add another constructor
public puzzleview(Context context, AttributeSet attrs){
super(context, attrs);
this.game=(Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
}
I would imagine that line 95 accesses something which hasn't been initialised. When the app. starts it will quite probably try and render puzzleview. At a guess, game hasn't been fully initialised at this point, and so the access to game.getTileString(i, j) fails in some way. You might like to have a flag in Game which tells puzzleview when getTileString is ready to be used, which you use in puzzleview.onDraw():
if (game.getTileStringsAvailable()) {
for (int i=0;i<9;i++){
for (int j = 0;j<9;j++){
canvas.drawText(this.game.getTileString(i, j), i * width + x, j * height + y, foreground);
}
}
}

Categories

Resources