So I've returned to the streetfighter libgdx clone And Ive managed to draw ken's animations. But, I realised once removing the background that two kens were being drawn one behind the other that you can only see when you jump (after removing background) this other ken sprite doesnt jump. but can move horizontally.
My question is, is it where I'm defining Ken or how have i managed to draw him twice?
I'm baffled...
ken class
public class Ken extends Player {
private static final int FRAME_COLS = 6, FRAME_ROWS = 1;
private static final int COLUMNS_KICK = 6;
private static final int COLUMNS_LEFT = 8;
private static final int COLUMNS_RIGHT = 8;
private static final int COLUMNS_JUMP = 10;
private static final int COLUMNS_PUNCH = 6;
private static final int COLUMNS_FRONTFLIP = 8;
private static final int COLUMNS_BACKFLIP = 8;
private static final int COLUMNS_CROUCH_PUNCH= 3;
private static final int COLUMNS_UPPERCUT = 9;
public static final int FRAME_FRONTFLIP = 1;
public static final int FRAME_BACKLIP = 1;
public enum State {
IDLE, LEFT, RIGHT, JUMP, DUCK, PUNCH, HIT, KICK, END, BLOCK
}
Animation<TextureRegion> walkAnimation;
Animation<TextureRegion> kickAnimation;
Animation<TextureRegion> punchAnimation;
Animation<TextureRegion> leftAnimation;
Animation<TextureRegion> rightAnimation;
Animation<TextureRegion> jumpAnimation;
Animation<TextureRegion> frontFlipAnimation;
Animation<TextureRegion> backFlipAnimation;
Animation<TextureRegion> crouchPunchAnimation;
Animation<TextureRegion> uppercutAnimation;
Texture walkSheet;
Texture kickSheet;
Texture punchSheet;
Texture leftSheet;
Texture rightSheet;
Texture jumpSheet;
Texture frontFlipSheet;
Texture backFlipSheet;
Texture crouchPunchSheet;
Texture uppercutSheet;
public Body body;
public World world;
boolean alive = true;
private final static int STARTING_X = 50;
private final static int STARTING_Y = 30;
TextureRegion reg;
float stateTime;
public Ken(GameScreen screen){
this.world = screen.getWorld();
defineKen();
createIdleAnimation();
kickAnimation();
punchAnimation();
lefttAnimation();
righttAnimation();
jumpAnimation();
uppercutAnimation();
crouchPunchAnimation();
frontFlipAnimation();
backFlipAnimation();
this.setPosition(STARTING_X, STARTING_Y);
}
public void createIdleAnimation() {
walkSheet = new Texture(Gdx.files.internal("ken/idle.png"));
TextureRegion[][] tmp = TextureRegion.split(walkSheet,
walkSheet.getWidth() / FRAME_COLS,
walkSheet.getHeight() / FRAME_ROWS);
TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
walkFrames[index++] = tmp[i][j];
}
}
walkAnimation = new Animation<TextureRegion>(0.1f, walkFrames);
stateTime = 0f;
reg=walkAnimation.getKeyFrame(0);
}
public void kickAnimation(){
kickSheet = new Texture(Gdx.files.internal("ken/kick_low.png"));
TextureRegion [][] tmp = TextureRegion.split(kickSheet, kickSheet.getWidth() / COLUMNS_KICK,
kickSheet.getHeight() / FRAME_ROWS);
TextureRegion[] kickFrames = new TextureRegion[COLUMNS_KICK * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
kickFrames[index++] = tmp[i][j];
}
}
kickAnimation = new Animation<TextureRegion>(8f, kickFrames);
stateTime = 6f;
reg = kickAnimation.getKeyFrame(1);
}
public void lefttAnimation(){
leftSheet = new Texture(Gdx.files.internal("ken/parry_b.png"));
TextureRegion [][] tmp = TextureRegion.split(leftSheet, leftSheet.getWidth() / COLUMNS_LEFT,
leftSheet.getHeight() / FRAME_ROWS);
TextureRegion[] leftFrames = new TextureRegion[COLUMNS_LEFT * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_LEFT; j++) {
leftFrames[index++] = tmp[i][j];
}
}
leftAnimation = new Animation<TextureRegion>(0.1f, leftFrames);
stateTime = 0f;
reg = punchAnimation.getKeyFrame(0);
}
public void righttAnimation(){
rightSheet = new Texture(Gdx.files.internal("ken/parry_f.png"));
TextureRegion [][] tmp = TextureRegion.split(rightSheet, rightSheet.getWidth() / COLUMNS_RIGHT,
rightSheet.getHeight() / FRAME_ROWS);
TextureRegion[] rightFrames = new TextureRegion[COLUMNS_RIGHT * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_RIGHT; j++) {
rightFrames[index++] = tmp[i][j];
}
}
rightAnimation = new Animation<TextureRegion>(0.1f, rightFrames);
stateTime = 0f;
reg = rightAnimation.getKeyFrame(0);
}
public void punchAnimation(){
punchSheet = new Texture(Gdx.files.internal("ken/punch.png"));
TextureRegion [][] tmp = TextureRegion.split(punchSheet, punchSheet.getWidth() / COLUMNS_PUNCH,
punchSheet.getHeight() / FRAME_ROWS);
TextureRegion[] punchFrames = new TextureRegion[COLUMNS_PUNCH * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_PUNCH; j++) {
punchFrames[index++] = tmp[i][j];
}
}
punchAnimation = new Animation<TextureRegion>(1f, punchFrames);
stateTime = 0f;
reg = punchAnimation.getKeyFrame(0);
}
public void jumpAnimation(){
jumpSheet = new Texture(Gdx.files.internal("ken/jump.png"));
TextureRegion [][] tmp = TextureRegion.split(jumpSheet, jumpSheet.getWidth() / COLUMNS_JUMP,
jumpSheet.getHeight() / FRAME_ROWS);
TextureRegion[] jumpFrames = new TextureRegion[COLUMNS_JUMP * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_JUMP; j++) {
jumpFrames[index++] = tmp[i][j];
}
}
jumpAnimation = new Animation<TextureRegion>(0.1f, jumpFrames);
stateTime = 0f;
reg = jumpAnimation.getKeyFrame(0);
}
public void frontFlipAnimation(){
frontFlipSheet = new Texture(Gdx.files.internal("ken/front_flip.png"));
TextureRegion [][] tmp = TextureRegion.split(frontFlipSheet, frontFlipSheet.getWidth() / COLUMNS_FRONTFLIP,
frontFlipSheet.getHeight() / FRAME_ROWS);
TextureRegion[] frontFlipFrames = new TextureRegion[COLUMNS_FRONTFLIP * FRAME_FRONTFLIP];
int index = 0;
for (int i = 0; i < FRAME_FRONTFLIP; i++) {
for (int j = 0; j < COLUMNS_FRONTFLIP; j++) {
frontFlipFrames[index++] = tmp[i][j];
}
}
frontFlipAnimation = new Animation<TextureRegion>(0.1f, frontFlipFrames);
stateTime = 0f;
reg = frontFlipAnimation.getKeyFrame(0);
}
public void backFlipAnimation(){
backFlipSheet = new Texture(Gdx.files.internal("ken/back_flip.png"));
TextureRegion [][] tmp = TextureRegion.split(backFlipSheet, backFlipSheet.getWidth() / COLUMNS_BACKFLIP,
backFlipSheet.getHeight() / FRAME_BACKLIP);
TextureRegion[] backFlipFrames = new TextureRegion[COLUMNS_BACKFLIP * FRAME_BACKLIP];
int index = 0;
for (int i = 0; i < FRAME_BACKLIP; i++) {
for (int j = 0; j < COLUMNS_BACKFLIP; j++) {
backFlipFrames[index++] = tmp[i][j];
}
}
backFlipAnimation = new Animation<TextureRegion>(0.1f, backFlipFrames);
stateTime = 0f;
reg = backFlipAnimation.getKeyFrame(0);
}
public void crouchPunchAnimation(){
crouchPunchSheet = new Texture(Gdx.files.internal("ken/crouch_punch.png"));
TextureRegion [][] tmp = TextureRegion.split(crouchPunchSheet, crouchPunchSheet.getWidth() / COLUMNS_CROUCH_PUNCH,
crouchPunchSheet.getHeight() / FRAME_ROWS);
TextureRegion[] crouchPunchFrames = new TextureRegion[COLUMNS_CROUCH_PUNCH * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_CROUCH_PUNCH; j++) {
crouchPunchFrames[index++] = tmp[i][j];
}
}
crouchPunchAnimation = new Animation<TextureRegion>(0.1f, crouchPunchFrames);
stateTime = 1f;
reg = crouchPunchAnimation.getKeyFrame(5);
}
public void uppercutAnimation(){
uppercutSheet = new Texture(Gdx.files.internal("ken/uppercut.png"));
TextureRegion [][] tmp = TextureRegion.split(uppercutSheet, uppercutSheet.getWidth() / COLUMNS_UPPERCUT,
uppercutSheet.getHeight() / FRAME_ROWS);
TextureRegion[] uppercutFrames = new TextureRegion[COLUMNS_UPPERCUT * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_UPPERCUT; j++) {
uppercutFrames[index++] = tmp[i][j];
}
}
uppercutAnimation = new Animation<TextureRegion>(0.1f, uppercutFrames);
stateTime = 0f;
reg = uppercutAnimation.getKeyFrame(0);
}
#Override
public void act(float delta) {
super.act(delta);
stateTime += delta;
// setX(body.getPosition().x);
setY(body.getPosition().y);
stateTime += delta;
reg = walkAnimation.getKeyFrame(stateTime,true);
if(Gdx.input.isKeyPressed(Input.Keys.A)){
reg = kickAnimation.getKeyFrame(stateTime, false);
this.addAction(Actions.moveTo(getX() +5, getY(), 1F));
}
if(Gdx.input.isKeyPressed(Input.Keys.S)){
reg = punchAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 2, getY(), 1F));
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
reg = leftAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 10, getY(), 1 / 10f ));
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
reg = rightAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 10, getY(), 1 /10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.UP)){
reg = jumpAnimation.getKeyFrame(stateTime, false);
body.applyLinearImpulse(new Vector2(0, 10), body.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.D)){
reg = frontFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 5, getY(), 1 / 10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.W)){
reg = backFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 5, getY(), 1 / 10F));
}
if(Gdx.input.isKeyPressed(Input.Keys.DOWN)&& Gdx.input.isKeyPressed(Input.Keys.S)){
reg = crouchPunchAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 2, getY(), 1f));
}
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
reg = uppercutAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 5, getY(), 1 / 10F));
}
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
}
private void defineKen(){
BodyDef bdef = new BodyDef();
bdef.position.set(20F, 6.5F);
bdef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bdef);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(20, 0f);
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(70, 1.0f);
groundBody.createFixture(groundBox, 0.0f);
groundBox.dispose();
PolygonShape shape = new PolygonShape();
shape.setAsBox(76 / 2 / 10f, 136 / 2 / 10f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0f;
body.createFixture(fixtureDef);
shape.dispose();
}
}
Game class
public class GameScreen extends AbstractScreen {
Ken ken;
private Texture background;
private Image backgroundImg;
private World world;
public GameScreen(BeatDemGame game) {
super(game);
init();
}
#Override
protected void init() {
world = new World(new Vector2(0, -40f), true);
initBackground();
}
private void initBackground() {
// background = new Texture("city_stage.gif");
// backgroundImg = new Image(background);
// backgroundImg.setPosition(0, 0);
// stage.addActor(backgroundImg);
initPlayer();
}
private void initPlayer() {
ken = new Ken(this);
ken.setSize(70,90);
ken.setDebug(true);
stage.addActor(ken);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
super.render(delta);
update();
stage.draw();
}
private void update() {
stage.act();
world.step(1 / 30f, 6, 2);
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
game.dispose();
}
public World getWorld() {
return world;
}
}
I don't want this effect obviously as I only need 1 ken. i don't understand why its being drawn twice eg. where in the code is this being executed ?If i put a background the ken that doesn't jump sits behind the background and you can't see it....
thanks
updated code
public class Ken extends Actor {
.....
#Override
public void act(float delta) {
super.act(delta);
// stateTime += delta;
// setX(body.getPosition().x);
setY(body.getPosition().y);
stateTime += delta;
reg = walkAnimation.getKeyFrame(stateTime,true);
if(Gdx.input.isKeyPressed(Input.Keys.A)){
reg = kickAnimation.getKeyFrame(stateTime, false);
this.addAction(Actions.moveTo(getX() +5, getY(), 1F));
}
if(Gdx.input.isKeyPressed(Input.Keys.S)){
reg = punchAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 2, getY(), 1F));
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
reg = leftAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 10, getY(), 1 / 10f ));
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
reg = rightAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 10, getY(), 1 /10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.UP)){
reg = jumpAnimation.getKeyFrame(stateTime, false);
body.applyLinearImpulse(new Vector2(0, 10), body.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.D)){
reg = frontFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 5, getY(), 1 / 10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.W)){
reg = backFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 5, getY(), 1 / 10F));
}
if(Gdx.input.isKeyPressed(Input.Keys.DOWN)&& Gdx.input.isKeyPressed(Input.Keys.S)){
reg = crouchPunchAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 2, getY(), 1f));
}
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
reg = uppercutAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 5, getY(), 1 / 10F));
}
}
#Override
public void draw(Batch batch, float parentAlpha) {
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
}
private void defineKen(){
BodyDef bdef = new BodyDef();
bdef.position.set(20F, 6.5F);
bdef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bdef);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(20, 0f);
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(70, 1.0f);
groundBody.createFixture(groundBox, 0.0f);
groundBox.dispose();
PolygonShape shape = new PolygonShape();
shape.setAsBox(76 / 2 / 10f, 136 / 2 / 10f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0f;
body.createFixture(fixtureDef);
shape.dispose();
}
}
I still get two of ken.
In your Ken class, you override the draw() method to draw Ken on your own but you also call super.draw() which also draws Ken.
Change:
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
}
to:
#Override
public void draw(Batch batch, float parentAlpha) {
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
}
because super.draw() already draw Ken and three lines later you draw Ken a second time with batch.draw()
How does your Player class look like? I currently see only one line where you are actually drawing a texture region to screen.
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
And my guess is, since you want to draw every "Player" to the screen you are drawing it there too. Because you are also calling the draw method of the player by having super.draw(batch, parentAlpha); it will be drawing both.
I wanted to draw a grid of quads with an animated colour property but ended up with code that is too slow just to create a basic structure of an image, not to mention to animate it. Also, the image is drawing, not as it finished to compute, but in the process by parts. How can I fix it? Here's onDraw(Canvas canvas) method:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
final int height = canvas.getHeight();
final int width = canvas.getWidth();
Bitmap.Config conf = Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(width, height, conf);
new Thread(() -> {
int cells_amount = 0;
float cells_vertical = 0;
float cells_horizontal = 0;
cells_vertical = (float) height / CELL_SIZE;
int y = 0;
if (cells_vertical % 1 > 0) {
y = Math.round(CELL_SIZE * -(cells_vertical % 1));
cells_vertical = (int) (cells_vertical + 1);
}
cells_horizontal = (float) width / CELL_SIZE;
int x = 0;
if (cells_horizontal % 1 > 0) {
x = Math.round(CELL_SIZE * -(cells_horizontal % 1));
cells_horizontal = (int) (cells_horizontal + 1);
}
cells_amount = (int) (cells_horizontal * cells_vertical);
Canvas c = new Canvas(bitmap);
c.drawColor(Color.BLACK);
int x_preserved = x;
Paint textPaint = new Paint();
textPaint.setColor(Color.parseColor("#EEEEEE"));
for (int i = 0; i < cells_amount; i++) {
Rect rect = new Rect(x, y, x + CELL_SIZE, y + CELL_SIZE);
Paint framePaint = new Paint();
framePaint.setColor(Color.parseColor("#1F1F1F"));
framePaint.setStyle(Paint.Style.STROKE);
framePaint.setStrokeWidth(1);
c.drawRect(rect, framePaint);
if (random.nextBoolean()) {
String output = String.format(Locale.getDefault(), "%d", "+");
int cx = (int) (x + (CELL_SIZE / 2) - (textPaint.measureText(output) / 2));
int cy = (int) ((y + (CELL_SIZE / 2)) - ((textPaint.descent() + textPaint.ascent()) / 2));
c.drawText(output, cx, cy, textPaint);
}
if (i % cells_horizontal == 0 && i >= cells_horizontal) {
y += CELL_SIZE;
x = x_preserved;
} else {
x += CELL_SIZE;
}
}
}).start();
canvas.drawBitmap(bitmap, 0, 0, null);
}
Here I have use 'HoloGraph' Library for Doughnut chart But Now I need to show with animation. Please suggest me How can I do it?
I have done without animation
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);
}
}
In Layout:
<com.example.piecharts.PieChart
android:id="#+id/pieChart"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.example.piecharts.PieChart>
I am developing game using canvas. I have drawn grid of circles using loop. I want to get x,y coordinates of circles. For that I have to make those circles clickable so that whenever player click on a circle it should return its coordinates. I will pass those coordinates to lineDraw() method for drawing line between those circles.
This loop is defining grid of circles:
for (int y=0;y<rows;y++)
{
for (int x=0;x<cols;x++)
{
canvas.drawCircle((x + 1) * dw, (y + 1) *(3* dh), 20, pDot);
}
}
Here dw is (displayWidth) and dh is (displayHeight). Please suggest how I should make these circles clickable?
I had played with this project a little after your previous questions. I'm sure this isn't the most optimized way to do this, but without knowing how you plan to implement the game logic, I think this is flexible enough to adapt. The following is your custom View class, which I've renamed Board, in keeping with Java naming conventions.
public class Board extends View
{
Paint pBack = new Paint();
Paint pDot = new Paint();
Paint pLine = new Paint();
int cols = 5;
int rows = 6;
// Default initialization = false
boolean[][] dots = new boolean[cols][rows];
int canWidth = 0;
int canHeight = 0;
float xStep = 0;
float yStep = 0;
float[] xCoords = new float[cols];
float[] yCoords = new float[rows];
public Board(Context context)
{
super(context);
pBack.setARGB(255, 255, 102, 0);
pDot.setARGB(255, 255, 255, 255);
pLine.setStrokeWidth(5);
pLine.setARGB(255, 90, 10, 0);
}
public void setDots(boolean[][] dotSelected)
{
this.dots = dotSelected;
}
public boolean[][] getDots()
{
return dots;
}
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
canWidth = w;
canHeight = h;
xStep = canWidth / (cols + 1);
yStep = canHeight / (rows + 1);
for (int y = 0; y < rows; y++)
{
yCoords[y] = (y + 1) * yStep;
}
for (int x = 0; x < cols; x++)
{
xCoords[x] = (x + 1) * xStep;
}
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawPaint(pBack);
// Grid, lines and box markings
for (int y = 0; y < rows; y++)
{
canvas.drawLine(xStep, yCoords[y], cols * xStep, yCoords[y], pDot);
for (int x = 0; x < cols; x++)
{
if (y == 0)
{
canvas.drawLine(xCoords[x], yStep, xCoords[x], rows * yStep, pDot);
}
if (dots[x][y])
{
boolean left = x > 0 && dots[x - 1][y];
boolean up = y > 0 && dots[x][y - 1];
if (left)
{
canvas.drawLine(xCoords[x], yCoords[y], xCoords[x - 1], yCoords[y], pLine);
}
if (up)
{
canvas.drawLine(xCoords[x], yCoords[y], xCoords[x], yCoords[y - 1], pLine);
}
if (left && up && dots[x - 1][y - 1])
{
canvas.drawCircle(xCoords[x] - xStep / 2, yCoords[y] - yStep / 2, 10, pLine);
}
}
}
}
// Dots
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < cols; x++)
{
canvas.drawCircle(xCoords[x], yCoords[y], 20, pDot);
if (dots[x][y])
{
canvas.drawCircle(xCoords[x], yCoords[y], 15, pBack);
}
}
}
}
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);
if (event.getAction() != MotionEvent.ACTION_DOWN)
return true;
int xNear = 0;
int yNear = 0;
float xMin = canWidth;
float yMin = canHeight;
for (int x = 0; x < cols; x++)
{
if (Math.abs(xCoords[x] - event.getX()) < xMin)
{
xMin = Math.abs(xCoords[x] - event.getX());
xNear = x;
}
}
for (int y = 0; y < rows; y++)
{
if (Math.abs(yCoords[y] - event.getY()) < yMin)
{
yMin = Math.abs(yCoords[y] - event.getY());
yNear = y;
}
}
dots[xNear][yNear] = !dots[xNear][yNear];
invalidate();
return true;
}
}
Store the data of your circles (for instance the position and the radius) in a list and check each of them for mouse collision(register a mouseeventlistener).
public class Circle
{
private int radius;
private int positionX;
private int positionY;
public Circle(int positionX, int positionY, int radius)
{
this.radius = radius;
this.positionX = positionX;
this.positionY = positionY;
}
public int getPositionX()
{
return this.positionX;
}
public int getPositionY()
{
return this.positionY;
}
public boolean contains(int posX, int posY)
{
int distanceX = this.positionX - posX;
int distanceY = this.positionY - posY;
return Math.sqrt((distanceX * distanceX) + (distanceY * distanceY)) <= this.radius;
}
I have a custom view
public GraphView(Context context, float[] values, String title, String[]horlabels, String[] verlabels, boolean type, int color) {
super(context);
if (values == null)
this.values = new float[0];
else
this.values = values;
if (title == null)
title = "";
else
this.title = title;
if (horlabels == null)
this.horlabels = new String[0];
else
this.horlabels = horlabels;
if (verlabels == null)
this.verlabels = new String[0];
else
this.verlabels = verlabels;
this.type = type;
paint = new Paint();
this.color = color;
}
#Override
protected void onDraw(Canvas canvas) {
float border = 20;
float horstart = border * 2;
float height = getHeight();
float width = getWidth() - 1;
float max = getMax();
float min = getMin();
float diff = max - min;
float graphheight = height - (2 * border);
float graphwidth = width - (2 * border);
paint.setTextAlign(Align.LEFT);
int vers = verlabels.length - 1;
for (int i = 0; i < verlabels.length; i++) {
paint.setColor(Color.DKGRAY);
float y = ((graphheight / vers) * i) + border;
canvas.drawLine(horstart, y, width, y, paint);
paint.setColor(Color.BLACK);
canvas.drawText(verlabels[i], 0, y, paint);
}
int hors = horlabels.length - 1;
for (int i = 0; i < horlabels.length; i++) {
paint.setColor(Color.DKGRAY);
float x = ((graphwidth / hors) * i) + horstart;
canvas.drawLine(x, height - border, x, border, paint);
paint.setTextAlign(Align.CENTER);
if (i==horlabels.length-1)
paint.setTextAlign(Align.RIGHT);
if (i==0)
paint.setTextAlign(Align.LEFT);
paint.setColor(Color.BLACK);
canvas.drawText(horlabels[i], x, height - 4, paint);
}
paint.setTextAlign(Align.CENTER);
canvas.drawText(title, (graphwidth / 2) + horstart, border - 4, paint);
if (max != min) {
paint.setColor(color);
if (type == BAR) {
float datalength = values.length;
float colwidth = (width - (2 * border)) / datalength;
for (int i = 0; i < values.length; i++) {
float val = values[i] - min;
float rat = val / diff;
float h = graphheight * rat;
canvas.drawRect((i * colwidth) + horstart, (border - h) + graphheight, ((i * colwidth) + horstart) + (colwidth - 1), height - (border - 1), paint);
}
} else {
float datalength = values.length;
float colwidth = (width - (2 * border)) / datalength;
float halfcol = colwidth / 2;
float lasth = 0;
for (int i = 0; i < values.length; i++) {
float val = values[i] - min;
float rat = val / diff;
float h = graphheight * rat;
if (i > 0)
canvas.drawLine(((i - 1) * colwidth) + (horstart + 1) + halfcol, (border - lasth) + graphheight, (i * colwidth) + (horstart + 1) + halfcol, (border - h) + graphheight, paint);
lasth = h;
}
}
}
}
private float getMax() {
float largest = Integer.MIN_VALUE;
for (int i = 0; i < values.length; i++)
if (values[i] > largest)
largest = values[i];
return largest;
}
private float getMin() {
float smallest = Integer.MAX_VALUE;
for (int i = 0; i < values.length; i++)
if (values[i] < smallest)
smallest = values[i];
return smallest;
}
and when i call
setContentView(graphView);
it's work good, but when i call
diagramRelativeLayout = (RelativeLayout)switcher.getChildAt(i).findViewById(R.id.diagramRelativeLayout);
diagramRelativeLayout.addView(graphView);
it's don't work.
Error:07-12 11:07:38.933: ERROR/AndroidRuntime(30488): java.lang.RuntimeException: Unable to resume activity {com.meters.src/com.meters.src.Main_Activity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
RelativeLayout contained in ViewFlipper. How i can add my view to this layout?
You don't have to add your view using code, you can do it in xml like any android view :
in your case just add the following code in xml where you wan't your view
<com.your.package.GraphView android:id="#+id/myGraphView" />
Then in your activity you can retrieve it using
GraphView myGV = (GraphView) findViewById(R.id.myGraphView);
A view can only have a single parent. The view that you are adding (I am guessing re-using ie. graphView) is already part of another view hierarchy. If you really want to reuse it (I would suggest you probably dont) then you have to detach it from its parent in its existing view hierarchy.
Add the line of code like as follows,
diagramRelativeLayout = (RelativeLayout)switcher.getChildAt(i).findViewById(R.id.diagramRelativeLayout);
diagramRelativeLayout.removeAllViewsInLayout(); // <-- Add this and try
diagramRelativeLayout.addView(graphView);
I did it, I just made xml with one layout, and added a reference to it in diagramRelativeLayout:
my xml:
<RelativeLayout
android:id = "#+id/diagramRelativeLayout"
android:background="#layout/button_style"
android:layout_width="fill_parent"
android:layout_height = "fill_parent"
android:layout_marginTop = "10sp"
android:layout_marginLeft = "5sp"
android:layout_marginRight = "5sp"
android:layout_marginBottom = "10sp"
android:gravity="center">
<include android:id="#+id/graph" layout="#layout/graph"/>
</RelativeLayout>
My java:
graphLayout = (RelativeLayout)switcher.getChildAt(i).findViewById(R.id.graph);
graphLayout.addView(graphView);