I created a helper class that will return Text object based on the custom font and text I give.
Here is code :
public class CustomFontTextHelper {
private Font font;
private ITexture fontTexture;
private Text text;
public Text getTextWithFont(String myText,String fontPath,BaseGameActivity activity,float x,float y,int fontsize,int color){
fontTexture = new BitmapTextureAtlas(activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR);
FontFactory.setAssetBasePath("fonts/");
this.font = FontFactory.createFromAsset(activity.getFontManager(), fontTexture, activity.getAssets(), fontPath, fontsize, true, color);
this.font.load();
text = new Text(x, y, this.font, myText, activity.getVertexBufferObjectManager());
return text;
}
}
Using this helper class I create a text and attach to my scene. Its working perfectly. But when I try to change the text using text.setText method it crashes.
Below is the code I use to change the text.
public class StartingScreen extends BaseGameActivity {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 720;
// ===========================================================
// Fields
// ===========================================================
public Text loadingPercentage;
public float percentLoaded;
public CustomFontTextHelper fontHelper;
#Override
public EngineOptions onCreateEngineOptions() {
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.PORTRAIT_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new Background(0, 0, 0));
fontHelper = new CustomFontTextHelper();
percentLoaded = 0;
loadingPercentage = fontHelper.getTextWithFont("0%", "MyriadPro-Cond.ttf", this, CAMERA_WIDTH-120, 100, 64, Color.BLACK);
scene.attachChild(loadingPercentage);
pOnCreateSceneCallback.onCreateSceneFinished(scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
pOnPopulateSceneCallback.onPopulateSceneFinished();
loadingPercentage.setText("5%");
new Thread(new Runnable(){
#Override
public void run() {
int incr;
for (incr = 0; incr <= 100; incr+=5) {
StartingScreen.this.runOnUpdateThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
StartingScreen.this.loadingPercentage.setText(Float.toString(StartingScreen.this.percentLoaded) + "%");
}
});
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
}
}
// TODO Auto-generated method stub
}
}).start();
// TODO Auto-generated method stub
}
Please help me with the code.
As far as I can see you are using AndEngine GLES2, so as Matim already said you can change the Text instance. The problem is that when you instantiate the Text object the first time you either need to include some text or better you should tell the object how many letters it has to hold (max).
so instead of
text = new Text(x, y, this.font, myText, activity.getVertexBufferObjectManager());
you do
int textLength = 4;
text = new Text(x, y, this.font, myText, textLength, activity.getVertexBufferObjectManager());
I just set the length to 4 since you use it as a percentage, which can only be between 0% and 100% so maximal 4 letters. Of course you can set the text length as you want, if you set it to 1000 and only put "hello" in your text, its fine (if you can, make them small to save memory) .
You just can't reset the text size afterwards – meaning, once you created a Text object with length 5 you can't put 6 letters in it, nor can you call something like setSize(6).. that's not working.
I hope this helps!
Christoph
As pointed out by game droid, the problem is with the text length. However I would like to answer this question and the next one at the same time. The next question is, how do I avoid the delay when changing the text from one value to another, and the solution is to initialize the text with all of the characters you plan to use, like so:
Text text = new Text(x, y, this.font, "1234567890%",activity.getVertexBufferObjectManager());
text.setText("0%");
This form of the constructor sets the maximum text length to whatever the length of the initial string is, so in this case 11.
Text is only set your text value, you can't change that text,
if you want change your text then use ChangeableText.
ChangeableText changeableText = new ChangeableText(x, y, Font, "Your Text");
yourscene.attachChild(changeableText);
changeableText.setText("Your New Text");
Related
This is my second game application using LibGdx framework and this is my first time to use a framework in android. I'm trying to understand how to use it.I have already done with the design in the main menu and my problem is the functionality of each button to switch screen. Any link tutorial or sample codes are much appreciated thank you and advance
Here is my code
MainScreen.java
public class MainScreen extends ApplicationAdapter implements Screen {
//Screen Size
private static final int WIDTH= 720;
private static final int HEIGHT= 1280;
Viewport viewport;
private Camera camera;
private Stage stage;
private TextureRegion myTextureRegion;
private TextureRegionDrawable myTexRegionDrawable;
private ImageButton playBtn;
private Texture Background,logo,exit,credits,help,option,play;
SpriteBatch spriteBatch;
Sprite sprite;
MyGdxGame game;
public MainScreen(final MyGdxGame game) {
this.game = game;
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
spriteBatch = new SpriteBatch();
camera = new PerspectiveCamera();
viewport = new ScreenViewport(camera);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Background = new Texture(Gdx.files.internal("backgroundimage.png")); //background image
//Menu Buttons
exit = new Texture(Gdx.files.internal("menu/exit.png"));
logo = new Texture(Gdx.files.internal("menu/logo.png"));
option = new Texture(Gdx.files.internal("menu/options.png"));
help = new Texture(Gdx.files.internal("menu/help.png"));
credits = new Texture(Gdx.files.internal("menu/credits.png"));
play = new Texture(Gdx.files.internal("menu/play.png"));
sprite = new Sprite(play);
sprite.setPosition(130,360);
sprite.setSize(0,0);
myTextureRegion = new TextureRegion(play);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
playBtn = new ImageButton(myTexRegionDrawable); //Set the button up
stage.addActor(playBtn); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
playBtn.addListener(new InputListener(){
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Button Pressed");
game.setScreen(new IngamedayOne());
}
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
stage.addActor(playBtn);
}
#Override
public void create(){
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage); //Start taking input from the ui
}
#Override
public void render(float delta) {
}
#Override
public void resize(int width, int height) {
// viewport.update(width, height);
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
spriteBatch.begin();
spriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, WIDTH, HEIGHT);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(exit,590,1140);
spriteBatch.draw(logo,125,600);
spriteBatch.draw(play,130,360);
spriteBatch.draw(option,170,100);
spriteBatch.draw(help,350,100);
spriteBatch.draw(credits,470,100);
stage.act(Gdx.graphics.getDeltaTime()); //Perform ui logic
spriteBatch.end();
//stage.draw(); //Draw the ui
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
Background.dispose();
logo.dispose();
exit.dispose();
}
}
My Second Screen
public class IngamedayOne extends ApplicationAdapter implements Screen {
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
private boolean peripheralAvailable;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
private Texture cat ,left_paw,right_paw,progressbar_background,progressbar_knob,pause,meter;
Texture carpet,desk,plants,square_carpet,shoes;
SpriteBatch spriteBatch;
Sprite sprite;
private Texture Background;
Viewport viewport;
private Camera camera;
private Stage stage;
// A variable for tracking elapsed time for the animation
float stateTime;
//Screen Size
private static final int WIDTH= 720;
private static final int HEIGHT= 1280;
public IngamedayOne() {
}
public IngamedayOne(MyGdxGame game) {
}
#Override
public void create() {
stage = new Stage();
spriteBatch = new SpriteBatch();
// Load the sprite sheet as a texture
cat = new Texture(Gdx.files.internal("cat.png"));
sprite = new Sprite(cat);
sprite.setPosition(0,0);
sprite.setSize(0,0);
peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
camera = new PerspectiveCamera();
viewport = new ScreenViewport(camera);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//Display Items
carpet = new Texture("equip/carpet2.png");
desk = new Texture("equip/Desk.png");
square_carpet = new Texture("equip/Carpet.png");
plants = new Texture("equip/Plants.png");
shoes = new Texture("equip/Shoes.png");
// Progressbar
progressbar_background = new Texture("progression_map.png");
progressbar_knob = new Texture("cat_head.png");
//pause
pause = new Texture("pause.png");
meter = new Texture("meter.png");
//background
Background = new Texture(Gdx.files.internal("floor.png")); //File from assets folder
//button controller
left_paw = new Texture(Gdx.files.internal("left_paw.png"));
sprite = new Sprite(left_paw);
right_paw = new Texture(Gdx.files.internal("right_paw.png"));
sprite = new Sprite(right_paw);
// Use the split utility method to create a 2D array of TextureRegions. This is
// possible because this sprite sheet contains frames of equal size and they are
// all aligned.
TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() / FRAME_COLS, cat.getHeight()/ FRAME_ROWS);
// Place the regions into a 1D array in the correct order, starting from the top
// left, going across first. The Animation constructor requires a 1D array.
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];
}
}
// Initialize the Animation with the frame interval and array of frames
walkAnimation = new Animation<TextureRegion>(0.200f, walkFrames);
// Instantiate a SpriteBatch for drawing and reset the elapsed animation
// time to 0
spriteBatch = new SpriteBatch();
stateTime = 0f;
}
#Override
public void show() {
}
#Override
public void render(float delta) {
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
}
#Override
public void render() {
// clear previous frame
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
// Get current frame of animation for the current stateTime
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.begin();
spriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, WIDTH, HEIGHT);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(square_carpet,150,2,408,800);
spriteBatch.draw(carpet,230,980,250,260);
spriteBatch.draw(desk,10,1150,160,260);
spriteBatch.draw(plants,500,700,200,260);
spriteBatch.draw(shoes,300,500,110,110);
spriteBatch.draw(meter,190,990);
spriteBatch.draw(progressbar_background,20,1170);
spriteBatch.draw(progressbar_knob,18,1170);
spriteBatch.draw(pause,580,1150);
spriteBatch.draw(left_paw,10,25);
spriteBatch.draw(right_paw,517,25);
spriteBatch.draw(currentFrame, 260, 120 ); // Draw current frame at (50, 50)
spriteBatch.end();
stage.act(); //acting a stage to calculate positions of actors etc
stage.draw(); //drawing it to render all
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() { // SpriteBatches and Textures must always be disposed
spriteBatch.dispose();
cat.dispose();
left_paw.dispose();
right_paw.dispose();
stage.dispose();
Background.dispose();
progressbar_background.dispose();
progressbar_knob.dispose();
}
}
Your game should possess only one ApplicationListener(called when your application created).
Let's suppose that is your MainScreen which extends ApplicationAdapter(Adapter class of ApplicationListener interface), then not extend your IngamedayOne class again by ApplicationAdapter. You only need to implement with Screen interface.
public class IngamedayOne implements Screen {
}
create() method comes from ApplicationListener interface so migrate your code that in inside create() method to show().
Take a look of this wiki for more clearance.
https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game
You should create actors to add to your stage (in this case buttons, like an ImageButton)
and then use the setScreen() function to change screens on button presses addClickListener()
You can read more about it here:
https://github.com/libgdx/libgdx/wiki/Scene2d
I'm just learning AndEngine Anchor center and I'm working my way through the cookbook. However I'm having some trouble with loading the images to the screen (code compiles fine). Trying to load 3 rectangles(30x40, 40x30,70x50) in the oncreateResources method, code compiles, but does not display images.Thanks
public class GameActivity extends BaseGameActivity {
// The following constants will be used to define the width and height
// of our game's camera view
private static final int WIDTH = 800;
private static final int HEIGHT = 480;
// Declare a Camera object for our activity
private Camera mCamera;
// Declare a Scene object for our activity
private Scene mScene;
#Override
public EngineOptions onCreateEngineOptions() {
// Define our mCamera object
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
// Declare & Define our engine options to be applied to our Engine
// object
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(),
mCamera);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
BitmapTextureAtlas mBitmapTextureAtlas = new BitmapTextureAtlas(mEngine.getTextureManager(), 120, 120);
ITextureRegion mRetangleOneTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, this, "rectangle_one.png", 10, 10);
ITextureRegion mRetangleTwoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, this, "rectangle_two.png", 50, 10);
ITextureRegion mRetangleThreeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, this, "rectangle_three.png", 10, 60);
mBitmapTextureAtlas.load();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
I haven't used the center anchor branch yet, but your problem seems to be that you need to create sprites with the loaded ITextures. Then, you need to attach those sprites in the scene.
I have this code:
public class GameActivity extends SimpleBaseGameActivity{
static final int CAMERA_WIDTH = 800;
static final int CAMERA_HEIGHT = 480;
public Font mFont;
public Camera mCamera;
public Scene mCurrentScene;
public static BaseActivity instance;
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
instance = this;
mCamera = new Camera(0,0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
}
#Override
protected void onCreateResources() {
// TODO Auto-generated method stub
mFont = FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32);
mFont.load();
}
#Override
protected Scene onCreateScene() {
// TODO Auto-generated method stub
mEngine.registerUpdateHandler(new FPSLogger());
mCurrentScene = new Scene();
mCurrentScene.setBackground(new Background(0.09804f, 0.7274f, 0.8f));
return mCurrentScene;
}
}
My Whole goal is to just get something on the screen, just a simple bitmap. Ive followed a bunch of tutorials on andengine on youtube and google, but for some reason when i start the basegameactivity it doesnt display anything at all just a blank white screen. I also downloaded an example from github and copied and pasted the code and the example gave me the same thing just a blank white screen. Can anyone help me? Id appreciate it :]
I think you are using GLES2 andengine branch and may be your phone is not supporting GLES2.
Hello I have just started with AndEngine. I have been working with a tutorial here. I thought it was pretty straightforward but I can't seem to get it to work properly. The purpose is simply to display a simple Sprite. I did the code precisely how the tutorial instructed but when I run the game, nothing loads at all. I threw in some Log.i statements and it doesn't appear that any of the basic methods (OnCreateResources etc...) run at all. I'm not getting any errors but the nothing is running either. Does anyone know what I am doing wrong?
(I hope this isn't a stupid question) Code is below:
public class GameMain extends BaseGameActivity {
Scene scene;
protected static final int CAMERA_WIDTH = 800;
protected static final int CAMERA_HEIGHT = 480;
BitmapTextureAtlas playerTexture;
ITextureRegion playerTextureRegion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
Log.i("TEST", "CREATE GAME");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game_main, menu);
return true;
}
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions options = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
Log.i("TEST", "LOADING GFX");
loadGFX();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
private void loadGFX() {
// TODO Auto-generated method stub
Log.i("TEST", "LOAD GFX");
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
playerTexture = new BitmapTextureAtlas(getTextureManager(), 64, 64);
playerTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(playerTexture, this, "star.png", 0, 0);
playerTexture.load();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
Log.i("TEST", "Scene Background");
this.scene = new Scene();
this.scene.setBackground(new Background(0, 125, 58));
pOnCreateSceneCallback.onCreateSceneFinished(this.scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
Sprite sPlayer = new Sprite(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2,
playerTextureRegion,
this.mEngine.getVertexBufferObjectManager());
sPlayer.setRotation(45.0f);
this.scene.attachChild(sPlayer);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
in a short look at the tutorial, i didn't see anything about overwriting the onCreate method, esp. the setContentView part could be wrong.
makes me wonder, that none of the Log.i calls appear in your log, did you set your log to a higher level than info?
let me take a deeper look, if these two hints where not right ;-)
So, I have created an android activity that draws a triangle on the canvas. I also added 4 menus(Color, Enlarge, Shrink, and Reset) to the VM. The color works fine but I'm not quite sure how to resize a triangle in android once that menu button is pressed.The assignment says to just fix the top point of the triangle, and then change the coordinates of the bottom two points of the triangle. Can anyone point me in the right direction on how to do that in Android?
Here's my code, although the implementation of enlarge, shrink, and reset are set up to work with a circle(project I did before), not a triangle. Please note that the "Color" menu works so no need to do that.
public class MainActivity extends Activity
{
final Context context = this;
private Graphics graphic;
private Dialog radiusDialog; //Creates dialog box declaration
private SeekBar red;
private SeekBar green;
private SeekBar blue;
private Button radiusButton;
private TextView progress1;
private TextView progress2;
private TextView progress3;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
graphic = new Graphics(this); //Create new instance of graphics view
setContentView(graphic); //Associates customized view with current screen
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) //This acts as a menu listener to override
{
switch(item.getItemId()) //returns menu item
{
case R.id.Color:
showDialog();
break;
case R.id.Shrink:
graphic.setRadius(graphic.getRadius() -1);
graphic.invalidate();
break;
case R.id.Enlarge:
graphic.setRadius(graphic.getRadius() +1);
graphic.invalidate();
break;
case R.id.Reset:
graphic.setColor(Color.CYAN);
graphic.setRadius(75);
graphic.invalidate();
break;
}
return super.onOptionsItemSelected(item);
}
void showDialog() //creates memory for dialog
{
radiusDialog = new Dialog(context);
radiusDialog.setContentView(R.layout.draw_layout); //binds layout file (radius) with current dialog
radiusDialog.setTitle("Select Color:");
red = (SeekBar)radiusDialog.findViewById(R.id.seekBar1);
green = (SeekBar)radiusDialog.findViewById(R.id.seekBar2);
blue = (SeekBar)radiusDialog.findViewById(R.id.seekBar3);
progress1 = (TextView)radiusDialog.findViewById(R.id.textView2);
progress2 = (TextView)radiusDialog.findViewById(R.id.textView4);
progress3 = (TextView)radiusDialog.findViewById(R.id.textView6);
mychange redC = new mychange();
red.setOnSeekBarChangeListener(redC);
mychange greenC = new mychange();
green.setOnSeekBarChangeListener(greenC);
tv = (TextView)radiusDialog.findViewById(R.id.textView7);
mychange c = new mychange();
blue.setOnSeekBarChangeListener(c);
radiusButton = (Button) radiusDialog.findViewById(R.id.button1);
radiusButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int color = Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress());
radiusDialog.dismiss();
setContentView(R.layout.activity_main);
setContentView(graphic);
graphic.setColor(color);//Create new instance of graphics view
graphic.invalidate();
}
});
radiusDialog.show(); //shows dialog on screen
}
public class mychange implements OnSeekBarChangeListener{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
int color = Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress());
tv.setBackgroundColor(color);
progress1.setText(String.valueOf(red.getProgress()));
progress2.setText(String.valueOf(green.getProgress()));
progress3.setText(String.valueOf(blue.getProgress()));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
}
Graphics Class to draw triangle
public class Graphics extends View
{
private Paint paint;
private int radius;
private int color;
public void setColor(int color)
{
this.color = color;
}
public Graphics(Context context) //creates custom view (constructor)
{
super(context);
paint = new Paint(); //create instance of paint
color = Color.CYAN;
paint.setStyle(Paint.Style.FILL); //draw filled shape
radius = 75;
}
#Override
protected void onDraw(Canvas canvas) //override onDraw method
{
super.onDraw(canvas);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
path.moveTo(230, 200);
path.lineTo(330, 300);
path.lineTo(130, 300);
path.close();
canvas.drawPath(path, paint);
}
void setRadius(int radius)
{
this.radius = radius;
invalidate(); //just like repaint method
}
public int getRadius()
{
return radius;
}
}
If the top coordinate remains fixed, you can change the height of the triangle to shrink/enlarge it.
Lets say the triangle is equilateral - all 3 sides have the same length. In this case:
So if the top vertex coordinates are (x, y), the bottom coordinates will be:
(x - side / 2, y + h)
And:
(x + side / 2, y + h)
So your path code should be written as:
float side = Math.sqrt(3) / 2 * height;
Path path = new Path();
path.moveTo(x, y);
path.lineTo(x - side / 2, y + height);
path.lineTo(x + side / 2, y + height);
path.close();