I have been trying to figure out a way to center text on a button, but can't find an easy, multi-purpose way to. I can do it, but it will only work for a certain string, not for any string. i would like to know if there is a way to center any string on a button. My button in this case is 185x50.
I have been able to center this button on the screen, like so:
buttonX = WIDTH / 2 - (screen.getRegionWidth() / 2);
buttonY = HEIGHT / 2 - (screen.getRegionHeight() / 2);
Any help would be much appreciated. :)
Updated the answer to libgdx version 1.7.1-SNAPSHOT:
The easiest way to do this, is to use the TextButton class from libgdx. The text from a TextButton is centered by default. This still works!
Updated example:
final BitmapFont font = new BitmapFont();
final String text = "Test";
final GlyphLayout layout = new GlyphLayout(font, text);
// or for non final texts: layout.setText(font, text);
final float fontX = objectX + (objectWidth - layout.width) / 2;
final float fontY = objectY + (objectHeight + layout.height) / 2;
font.draw(batch, layout, fontX, fontY);
Outdated example:
This no longer works!
If you do not want to use it, you can get the font width and height with:
font.getBounds("Test text");
So you can do something like this:
String fontText = "";
fontX = buttonX + buttonWidth/2 - font.getBounds(fontText).width/2;
fontY = buttonY + buttonHeight/2 + font.getBounds(fontText).height/2;
For the newer version of libgdx the function BitMapFont.getBounds() isn't there in api anymore. You can use GlyphLayout to get bounds.For example,
BitmapFont font;
SpriteBatch spriteBatch;
//... Load any font of your choice first
FreeTypeFontGenerator fontGenerator = new FreeTypeFontGenerator(
Gdx.files.internal("myFont.ttf")
);
FreeTypeFontGenerator.FreeTypeFontParameter freeTypeFontParameter =
new FreeTypeFontGenerator.FreeTypeFontParameter();
freeTypeFontParameter.size = size;
fontGenerator.generateData(freeTypeFontParameter);
font = fontGenerator.generateFont(freeTypeFontParameter);
//Initialize the spriteBatch as requirement
GlyphLayout glyphLayout = new GlyphLayout();
String item = "Example";
glyphLayout.setText(font,item);
float w = glyphLayout.width;
font.draw(spriteBatch, glyphLayout, (Game.SCREEN_WIDTH - w)/2, y);
Try the following:
label.setPosition(Gdx.graphics.getWidth()/2-(label.getPrefWidth()/2),Gdx.graphics.getHeight()-(label.getPrefHeight()/2));
Related
I've been working on this snippet:
public static final TermCriteria KMEANS_CRITERIA = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER, 10, 1.0);
private double getColours(Mat image) {
var labels = new MatOfFloat();
var reshape = new Mat();
image.convertTo(reshape, CvType.CV_32FC3);
reshape = reshape.reshape(1,1);
System.out.println("reshape = " + reshape.toString());
var centers = new Mat();
Core.kmeans(reshape, 3, labels, KMEANS_CRITERIA, 3, Core.KMEANS_RANDOM_CENTERS, centers);
}
The problem is, reshape = reshape.reshape(1,1); converts the image from CV_32FC3[X, Y] to CV_32FC1[X*Y] - it goes from 3 channels (R,G,B) to 1 channel.
I think this is the final problem to solve, in order to get the KMeans clustering working.
Anyone know how to fix this, so that I can get a final result of centers = CV_8UC3[3] (the 3 colour clusters)
I am trying to set the registration point of an image to the bottom centre so it can rotate around that point. So far my code looks like this:
var img = new createjs.Bitmap("img.png");
img.x = 200;
img.y = 180;
img.scaleX = 0.35;
img.scaleY = 0.35;
img.regX = img.width/2;
img.regY = 0;
img.rotation = 15;
canvas.addChild(img);
I tried changing the numbers of img.regY but I can't seem to get it correct.
What is redBalloon.width?
The best approach is to wait until the image is loaded, and then use its natural width.
img.image.onload = function() {
img.regX = img.image.naturalWidth;
img.regY = img.image.naturalHeight;
}
Hope that helps.
I am coding a simple diagram that parses a .tsv file that has 6 columns and 9 rows. I am attempting to put some text on my diagram that is coloured according to the data existing in the third column. I am able to get all the colours on the screen, but for some reason, the text that ends up red is the text corresponding to the row (in the tsv file) BELOW the row whose text I want to be red. For example, while I want the Liberal candidate to have a fill of (200,60,60), the Parti Quebecois candidate appearing in the row below instead becomes red. Following, the New Dem party candidate ends up with the fill of (155,191,219). The code appears as follows:
PImage mapOfCanada; // background map
Premier[] premiers; // premiers data
void setup() {
size(800, 800);
// modified mapOfCanada from http://www.theblog.ca/map-canada
mapOfCanada = loadImage("bigmapofcanada.png");
// from http://en.wikipedia.org/wiki/List_of_current_Canadian_first_ministers
Table table = new Table("premiers.tsv");
int rows = table.getRowCount();
premiers = new Premier[rows];
// read through each row of the source data to populate our premiers array
for (int i=0; i<rows; i++) {
String name = table.getString(i, 0);
String province = table.getString(i, 1);
String party = table.getString(i, 2);
String imgFile = table.getString(i, 3);
PImage img = loadImage(imgFile);
float x = table.getFloat(i,4);
float y = table.getFloat(i,5);
premiers[i] = new Premier(name, province, party, img, x, y);
}
}
void draw() {
background(255);
// draw the background image with a light tint
tint(255, 25);
image(mapOfCanada, 0, 0);
// draw each premier
noTint();
for (Premier premier : premiers) {
image(premier.img, premier.x, premier.y);
}
//drawing lines for those premier images that cannot fit in the alloted province space
line(158,560,145,460); //Alberta
line(300,560,340,500); //Manitoba
line(650,365,670,410); //Newfoundland
line(750,385,710,535); //PEI
line(730,575,720,550); //Nova Scotia
line(670,595,680,560); //New Brunswick
//adding text labels
for (Premier premier : premiers) { //reading through the source data in a loop
textSize(10); //making the text size small yet readable
textAlign(CENTER); //making sure the text is centered above the image
text(premier.name, premier.x+50, premier.y-10); //positioning the text in relation to the x and y coordinates on the source data
{
String string1 = new String("Liberal");
String string2 = new String("Parti Quebecois");
String string3 = new String("New Democratic");
String string4 = new String ("Progressive Conservative");
String string5 = new String ("Saskatchewan Party");
String string6 = new String ("Yukon Party");
if (premier.party.equals("Liberal")) {
fill(200,60,60);
}
else if (premier.party.equals("Parti Quebecois")) {
fill(155,191,219);
}
else if (premier.party.equals("New Democratic")) {
fill(180,151,107);
}
else if(premier.party.equals("Progressive Conservative")) {
fill(96,104,250);
}
else if(premier.party.equals("Saskatchewan Party")) {
fill (107,180,119);
}
else if(premier.party.equals("Yukon Party")) {
fill (47,85,232);
}
else {
fill (0,0,0);
}
}
}
}
class Premier {
String name, province, party;
PImage img; // this is the thumbnail image
float x, y; // these are the coordinates for the thumbnail
Premier(String name, String province, String party, PImage img, float x, float y) {
this.name = name;
this.province = province;
this.party = party;
this.img = img;
this.x = x;
this.y = y;
}
}
Any help re: what I'm doing wrong would be much appreciated! I've edited the post to feature the full code.
Thank you!
Seems like a one off error in the loop that wraps the code that you have posted.
According to the description of an issue you're having, it may be related to indexing error - i.e. using 0-based indexing where it's actually 1-based or vice versa. But without the loop code and fill() code it will be very hard to pinpoint the problem.
Is anyone familiar with AndEngine and loading svg's?
Right now i am trying to load a background for a scene and it doesnt appear at all for some reason..
Here is th code i am using to load the SVG and attach it to the scene.
//In my onLoadResources method
this.mBuildableTexture = new BuildableBitmapTexture(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
SVGTextureRegionFactory.setAssetBasePath("gfx/");
this.mSVGTestTextureRegions = SVGTextureRegionFactory.createFromAsset(this.mBuildableTexture, this, "background.svg", 16, 16);
//OnLoadScene method
final BaseTextureRegion baseTextureRegion = this.mSVGTestTextureRegions;
if(baseTextureRegion instanceof TextureRegion) {
final TextureRegion Region = (TextureRegion)baseTextureRegion;
final float centerX = this.mCamera.getWidth() / 2;
final float centerY = this.mCamera.getHeight() / 2;
final float x = centerX - SIZE * 0.5f;
final float y = centerY - SIZE * 0.5f;
Sprite backgroundSprite = new Sprite(x,y,SIZE,SIZE,Region);
/*protected void onInitDraw(final GL10 pGL)
{
super.onInitDraw(pGL);
GLHelper.enableTextures(pGL);
GLHelper.enableTexCoordArray(pGL);
GLHelper.enableDither(pGL);
}
};*/
mScene.setBackground(new SpriteBackground(0.0f,0.0f,0.0f,backgroundSprite));
backgroundSprite.setIgnoreUpdate(true);
}
Are you including the following statements in your code in loadResources:
try {
this.mBuildableTexture.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
} catch (final TextureAtlasSourcePackingException e) {
Debug.e(e);
}
this.mEngine.getTextureManager().loadTexture(this.mBuildableTexture);
Imo the naming of the BlackPawnTextureAtlasBuilder class is pretty intuitive, as:
It is an implementation ITextureAtlasBuilder interface
The class javadoc says:
#author Jim Scott (BlackPawn)
#since 16:03:01 - 12.08.2010
#see http://www.blackpawn.com/texts/lightmaps/default.html
:-)
In my Swing application, users enter styled text into a JTextPane which uses an RTFEditorKit (HTML is also a possibility).
I then need to render many of these styled notes at specific coordinates in a custom component.
I would think the View.paint method would be helpful here, but I'm not able to create a usable View object.
I have the following method:
public View createView() throws IOException, BadLocationException {
RTFEditorKit kit = new RTFEditorKit();
final Document document = kit.createDefaultDocument();
kit.read(new ByteArrayInputStream(text.getBytes("UTF-8")), document, 0);
return kit.getViewFactory().create(document.getDefaultRootElement());
}
This returns a javax.swing.text.BoxView with the following attributes:
majorAxis = 1
majorSpan = 0
minorSpan = 0
majorReqValid = false
minorReqValid = false
majorRequest = null
minorRequest = null
majorAllocValid = false
majorOffsets = {int[0]#2321}
majorSpans = {int[0]#2322}
minorAllocValid = false
minorOffsets = {int[0]#2323}
minorSpans = {int[0]#2324}
tempRect = {java.awt.Rectangle#2325}"java.awt.Rectangle[x=0,y=0,width=0,height=0]"
children = {javax.swing.text.View[1]#2326}
nchildren = 0
left = 0
right = 0
top = 0
bottom = 0
childAlloc = {java.awt.Rectangle#2327}"java.awt.Rectangle[x=0,y=0,width=0,height=0]"
parent = null
elem = {javax.swing.text.DefaultStyledDocument$SectionElement#2328}"BranchElement(section) 0,35\n"
Note that parent = null and nchildren = 0. This means there's nothing really useful there. I can hack together something by calling JTextPane.getUI().paint, but the text pane needs to be visible, and this feels like the wrong way to do it.
Is there any way to get a visual representation of the RTF content without rendering the actual JTextPane?
This code sort of works, but seems less than ideal. Is there a better way to do it? Also, what's a good way to render the text somewhere other than 0,0 on the graphics?
private static void testRtfRender() {
String s = "{\\rtf1\\ansi\n" +
"{\\fonttbl\\f0\\fnil Monospaced;\\f1\\fnil Lucida Grande;}\n" +
"\n" +
"\\f1\\fs26\\i0\\b0\\cf0 this is a \\b test\\b0\\par\n" +
"}";
JTextPane pane = new JTextPane();
pane.setContentType("text/rtf");
pane.setText(s);
final Dimension preferredSize = pane.getUI().getPreferredSize(pane);
int w = preferredSize.width;
int h = preferredSize.height;
pane.setSize(w, h);
pane.addNotify();
pane.validate();
// would be nice to use this box view instead of instantiating a UI
// however, unless you call setParent() on the view it's useless
// What should the parent of a root element be?
//BoxView view = (BoxView) pane.getEditorKit().getViewFactory().create(pane.getStyledDocument().getDefaultRootElement());
//view.paint(d, new Rectangle(w, h));
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
final Graphics2D d = img.createGraphics();
d.setClip(0, 0, w, h); // throws a NullPointerException if I leave this out
pane.getUI().paint(d, pane);
d.dispose();
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
}
Check out the ScreenImage class which allows you to create a BufferedImage of any Swing component. It should also work for Swing components that are not visible, but yes you do have to do the rendering first.