直接上代码:
package com.ef.smallstar.libgdx.widget;
import android.content.res.Resources;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.ef.smallstar.EFApplication;
import com.ef.smallstar.R;
import com.ef.smallstar.libgdx.base.BaseGdxActor;
/**
* Created by ext.danny.jiang on 17/4/17.
* <p>
* A Widget currently used in the UnitMap, shown as a CIRCLE shape
* if text not null, there would be a text drawn in the center of the circle
*/
public class GdxCircle extends BaseGdxActor {
private float centerX;
private float centerY;
private String text;
private float radius;
private ShapeRenderer sr;
private BitmapFont bitmapFont;
private int textWidth;
private int textHeight;
public GdxCircle(TextureRegion region) {
super(region);
}
public GdxCircle(float x, float y, float radius, BitmapFont bitmapFont) {
this(x, y, radius, null, bitmapFont);
}
public GdxCircle(float x, float y, float radius, String text, BitmapFont bitmapFont) {
this.centerX = x;
this.centerY = y;
this.radius = radius;
this.text = text;
//DANNY ADD:make the Actor's position the same as Circle which ShareRenderer has renderer
setPosition(centerX - radius, centerY - radius);
setSize(radius * 2, radius * 2);
Resources resources = EFApplication.getInstance().getResources();
sr = new ShapeRenderer();
sr.setColor(Color.valueOf(resources.getString(R.string.default_lesson_circle)));
this.bitmapFont = bitmapFont;
}
@Override
public void act(float delta) {
super.act(delta);
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
if (sr != null) {
batch.end();
sr.setProjectionMatrix(batch.getProjectionMatrix());
sr.setTransformMatrix(batch.getTransformMatrix());
sr.begin(ShapeRenderer.ShapeType.Filled);
sr.circle(centerX, centerY, radius);
sr.end();
batch.begin();
if (text != null) {
textWidth = bitmapFont.getData().getGlyph(text.charAt(0)).width;
textHeight = bitmapFont.getData().getGlyph(text.charAt(0)).height;
bitmapFont.draw(batch, text, centerX - textWidth / 2, centerY + textHeight / 2);
}
}
}
public void setCircleColor(Color circleColor) {
if (sr != null) {
sr.setColor(circleColor);
}
}
public void setCenterPosition(float centerX, float centerY) {
this.centerX = centerX;
this.centerY = centerY;
}
public void setRadius(float radius) {
this.radius = radius;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public float getCenterX() {
return centerX;
}
public float getCenterY() {
return centerY;
}
public float getRadius() {
return radius;
}
}
使用方法 直接添加到Stage中即可,如下所示:
GdxCircle circle = new GdxCircle();
Stage stage = new Stage();
stage.addActor(circle);