Related
I'm remaking the design of an old javafx app and I need to include an icon for the wifi strength. The designer sent me an svg icon for that, and I thought it was smarter to just keep one icon and use different fill colors for the 3 bars depending of the said wifi strength.
I found a nice approach for that, and it works quite well until you need to resize the wifi icon. It seems like even if I change the -fx-pref-width (or height, or min/max) the svg icon keeps its size.
I also tried to resize each svg path one by one but it only goes messy with the spaces between them. And using a unique shape to resize later is not an option, as I need at least 2 colors. FYI the goal is to apply a 5em or 3em size depending of the context.
Here's the code I currently have, where everything looks great if you don't matter the icon size :
public class WifiStrengthRegion extends Pane {
public WifiStrengthRegion() {
getStyleClass().setAll("wifi-strength");
SVGPath round = new SVGPath();
SVGPath bar1 = new SVGPath();
SVGPath bar2 = new SVGPath();
SVGPath bar3 = new SVGPath();
round.setContent("M253.5,336.5c-18.9,0-34.2,15.3-34.2,34.1c0,18.8,15.4,34.1,34.2,34.1c18.9,0,34.2-15.3,34.2-34.1 C287.7,351.8,272.4,336.5,253.5,336.5z");
bar1.setContent("M337,290.1c-22.3-22.3-51.9-34.5-83.5-34.5c-31.4,0-61,12.2-83.3,34.3c-9,9-9,23.5,0,32.5 c4.4,4.4,10.2,6.8,16.3,6.8c6.2,0,11.9-2.4,16.3-6.7c13.6-13.5,31.6-20.9,50.7-20.9c19.2,0,37.3,7.5,50.8,21 c4.4,4.4,10.2,6.8,16.3,6.8c6.2,0,11.9-2.4,16.3-6.7C346,313.6,346,299,337,290.1z");
bar2.setContent("M389.3,238c-36.3-36.2-84.5-56.1-135.8-56.1c-51.2,0-99.3,19.9-135.6,55.9c-4.4,4.3-6.8,10.1-6.8,16.3 c0,6.1,2.4,11.9,6.7,16.3c4.4,4.3,10.2,6.7,16.3,6.7c6.2,0,11.9-2.4,16.3-6.7c27.5-27.4,64.1-42.5,103-42.5 c39,0,75.6,15.1,103.1,42.6c4.4,4.4,10.2,6.8,16.3,6.8c6.2,0,12-2.4,16.3-6.7c4.4-4.3,6.8-10.1,6.8-16.3 C396,248.1,393.6,242.3,389.3,238z");
bar3.setContent("M444.3,183.2c-50.9-50.8-118.7-78.8-190.8-78.8c-72,0-139.7,27.9-190.6,78.6c-9,9-9,23.5,0,32.5 c4.4,4.3,10.2,6.7,16.3,6.7c6.2,0,12-2.4,16.3-6.7c42.2-42,98.3-65.2,158-65.2c59.7,0,115.9,23.2,158.1,65.3 c4.4,4.3,10.2,6.7,16.3,6.7c6.2,0,11.9-2.4,16.3-6.7C453.2,206.7,453.3,192.1,444.3,183.2z");
round.getStyleClass().add("wifi-base");
bar1.getStyleClass().add("wifi-bar1");
bar2.getStyleClass().add("wifi-bar2");
bar3.getStyleClass().add("wifi-bar3");
this.getChildren().addAll(round, bar1, bar2, bar3);
}
public void setWifiStrength(Integer strength) {
if (strength == null) {
setManaged(false);
setVisible(false);
} else {
setManaged(true);
setVisible(true);
getStyleClass().removeAll("wifi-excellent", "wifi-good", "wifi-fair", "wifi-weak", "wifi-off");
if (strength < 0 && strength >= -100) {
if (strength >= -50) {
getStyleClass().add("wifi-excellent");
} else if (strength >= -70) {
getStyleClass().add("wifi-good");
} else if (strength >= -80) {
getStyleClass().add("wifi-fair");
} else {
getStyleClass().add("wifi-weak");
}
} else {
getStyleClass().add("wifi-off");
}
}
}
}
(and then a css stylesheet applies -fx-fill to each .wifi-barX depending of the main element class)
And here is an example of how the svg icon looks like:
I'm a very beginner in Java (and obv JavaFX), so any constructive criticism will be appreciated!
If you want to resize only (I hope this works):
public void resize(SVGPath svg, double width, double height) {
this.width = width;
this.height = height;
double originalWidthR = svg.prefWidth(-1);
double originalHeightR = svg.prefHeight(originalWidthR);
double scaleXr = width / originalWidthR;
double scaleYr = height / originalHeightR;
svg.setScaleX(scaleXr);
svg.setScaleY(scaleYr);
}
And if you want to set bounds use this:
public void setBounds(SVGPath svg, double width, double height, double x, double y) {
this.width = width;
this.height = height;
double originalWidthR = svg.prefWidth(-1);
double originalHeightR = svg.prefHeight(originalWidthR);
double scaleXr = width / originalWidthR;
double scaleYr = height / originalHeightR;
svg.setScaleX(scaleXr);
svg.setScaleY(scaleYr);
svg.setLayoutX((originalWidthR - width) + x);
svg.setLayoutY((originalHeightR - height) + y);
}
Hello dear developers,
Im using xamarin (monotouch) i want to draw circle image view like google plus profile image or like otherones...
I was search on net but didnt find useful thing.
Somebody help me?
Thank you..
For your purposes you can use UIView or UIButton. With UIButton it is easier to handle touch events.
The basic idea is to create a UIButton with specific coordinates and size and set the CornerRadius property to be one half of the size of the UIButton (assuming you want to draw a circle, width and height will be the same).
Your code could look something like this (in ViewDidLoad of your UIViewController):
// define coordinates and size of the circular view
float x = 50;
float y = 50;
float width = 200;
float height = width;
// corner radius needs to be one half of the size of the view
float cornerRadius = width / 2;
RectangleF frame = new RectangleF(x, y, width, height);
// initialize button
UIButton circularView = new UIButton(frame);
// set corner radius
circularView.Layer.CornerRadius = cornerRadius;
// set background color, border color and width to see the circular view
circularView.BackgroundColor = UIColor.White;
circularView.Layer.CornerRadius = cornerRadius;
circularView.Layer.BorderColor = UIColor.Red.CGColor;
circularView.Layer.BorderWidth = 5;
// handle touch up inside event of the button
circularView.TouchUpInside += HandleCircularViewTouchUpInside;
// add button to view controller
this.View.Add(circularView);
At last implement the event handler (define this method somewhere in your UIViewController:
private void HandleCircularViewTouchUpInside(object sender, EventArgs e)
{
// initialize random
Random rand = new Random(DateTime.Now.Millisecond);
// when the user 'clicks' on the circular view, randomly change the border color of the view
(sender as UIButton).Layer.BorderColor = UIColor.FromRGB(rand.Next(255), rand.Next(255), rand.Next(255)).CGColor;
}
Xamarin.iOS is a wrapper over Cocoa Touch on UI side,
https://developer.apple.com/technologies/ios/cocoa-touch.html
So to draw circle you need to use the Cocoa Touch API, aka CoreGraphics,
http://docs.xamarin.com/videos/ios/getting-started-coregraphics/
I am supposed to implement a gesture-based menu in which you scroll through a horizontal list of items by panning or flinging through them. This kind of menus is very common in smart phone games. Example case would be Cut the Rope where you select box (Cardboard box, Fabric box) or Angry Birds where you select the set of levels (Poached Eggs, Mighty Hoax).
What I am thinking is that I'll have to do some complex physics calculations and give velocities and accelerations to menu items based on the gestures. Any better solutions? I am using libgdx btw.
I don't think you'd need to go through all that to implement a simple menu! It's all about defining offsets for various items (I'll just assume you want Cut the Rope-style menus, with only one entry in sight at a given moment (excluding transitions)) and then tweening between those offsets whenever a flick is detected!
You seem to have the gesture system all wired up, so right now, we just need to figure out how to display the menu. For simplicity's sake, we'll just assume that we don't want the menu to wrap around.
We'll start by envisioning what this menu will look like, in our heads. It would be just like a filmstrip which passes through the phone and can be seen through the screen.
phone ("stuff" is currently selected)
========
|---------------| |-------|
| Start | About | Stuff | Quit |
|---------------| |-------|
| |
| |
| |
========
We'll just assume that the screen width is w and, consequently, all menu entries are exactly that width (think Cut the Rope again!).
Now, when "Start", is to be displayed, we should just render the flimstrip on the screen starting with the first element, "Start", while the rest would, theoretically, lie to the right of the screen. This will be considered the basic case, rendering the menu with the offset = 0.
Yes, yes, this offset will be the key to our little slidey-slidey menu! Now, it's pretty obvious that when about is selected, we'll just have to offset the "filmstrip" to the left by one "frame", and here offset = - 1 * frameWidth. Our example case illustrated by my brilliant ASCII art has the third menu item selected, and since the frames are indexed starting from 0, we'll just subtract two times the frameWidth and get the desired offset. We'll just render the menu starting at offset = -2 * frameWidth.
(Obviously you can just compute frameWidth in advance, by using the API to fetch the screen width, and then just drawing the menu element text/ graphic centered).
So this is pretty simple:
the user sweeps to the left, we need to get to the menu closer to offset 0, we reduce the index of the selected entity by one and the menu then jumps to the right position
the user sweeps to the right, we increase the index (obviously as long as it doesn't go over the number of menu elements - 1)
But what about smooth tweens?
Libgdx thankfully has interpolations all set for nice little tweens. We just need to take care of a few things so we don't shoot ourselves in the leg. I'll list them here.
One quick note:
The Cut the Rope level selector works a tad differently than what I'm saying here. It doesn't just react to flicks (pre-defined gestures), rather it's more sensitive. You can probably achieve a similar effect by playing with offsets and tracking the position of the finger on the screen. (If the user dragged a menu entry too much to the left/right, transition to the previous/next automatically) Friendly advice: just set up a simple, working menu, and leave details like this towards the end, since they can end up taking a lot of time! :P
Alright, back on track!
What we have now is a way to quickly switch between offsets. We just need to tween. There are some additional members that come into play, but I think they're pretty self-explanatory. While we're transitioning between two elements, we remember the "old" offset, and the one we're heading towards, as well as remembering the time we have left from the transition, and we use these four variables to compute the offset (using a libgdx interpolation, exp10 in this case) at the current moment, resulting in a smooth animation.
Let's see, I've created a quick'n'dirty mock-up. I've commented the code as best as I could, so I hope the following snippet speaks for itself! :D
import java.util.ArrayList;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
public class MenuManager {
// The list of the entries being iterated over
private ArrayList<MenuEntry> entries = new ArrayList<>();
// The current selected thingy
private int index;
// The menu offset
private float offset = 0.0f;
// Offset of the old menu position, before it started tweening to the new one
private float oldOffset = 0.0f;
// What we're tweening towards
private float targetOffset = 0.0f;
// Hardcoded, I know, you can set this in a smarter fashion to suit your
// needs - it's basically as wide as the screen in my case
private float entryWidth = 400.0f;
// Whether we've finished tweening
private boolean finished = true;
// How much time a single transition should take
private float transitionTimeTotal = 0.33f;
// How much time we have left from the current transition
private float transitionTimeLeft = 0.0f;
// libgdx helper to nicely interpolate between the current and the next
// positions
private Interpolation interpolation = Interpolation.exp10;
public void addEntry(MenuEntry entry) {
entries.add(entry);
}
// Called to initiate transition to the next element in the menu
public void selectNext() {
// Don't do anything if we're still animationg
if(!finished) return;
if(index < entries.size() - 1) {
index++;
// We need to head towards the next "frame" of the "filmstrip"
targetOffset = oldOffset + entryWidth;
finished = false;
transitionTimeLeft = transitionTimeTotal;
} else {
// (does nothing now, menu doesn't wrap around)
System.out.println("Cannot go to menu entry > entries.size()!");
}
}
// see selectNext()
public void selectPrevious() {
if(!finished) return;
if(index > 0) {
index --;
targetOffset = oldOffset - entryWidth;
finished = false;
transitionTimeLeft = transitionTimeTotal;
} else {
System.out.println("Cannot go to menu entry <0!");
}
}
// Called when the user selects someting (taps the menu, presses a button, whatever)
public void selectCurrent() {
if(!finished) {
System.out.println("Still moving, hold yer pants!");
} else {
entries.get(index).select();
}
}
public void update(float delta) {
if(transitionTimeLeft > 0.0f) {
// if we're still transitioning
transitionTimeLeft -= delta;
offset = interpolation.apply(oldOffset, targetOffset, 1 - transitionTimeLeft / transitionTimeTotal);
} else {
// Transition is over but we haven't handled it yet
if(!finished) {
transitionTimeLeft = 0.0f;
finished = true;
oldOffset = targetOffset;
}
}
}
// Todo make font belong to menu
public void draw(SpriteBatch spriteBatch, BitmapFont font) {
if(!finished) {
// We're animating, just iterate through everything and draw it,
// it's not like we're wasting *too* much CPU power
for(int i = 0; i < entries.size(); i++) {
entries.get(i).draw((int)(i * entryWidth - offset), 100, spriteBatch, font);
}
} else {
// We're not animating, just draw the active thingy
entries.get(index).draw(0, 100, spriteBatch, font);
}
}
}
And I believe a simple text-based menu entry that can draw itself would suffice! (do mind the dirty hard-coded text-wrap width!)
public class MenuEntry {
private String label;
// private RenderNode2D graphic;
private Action action;
public MenuEntry(String label, Action action) {
this.label = label;
this.action = action;
}
public void select() {
this.action.execute();
}
public void draw(int x, int y, SpriteBatch spriteBatch, BitmapFont font) {
font.drawMultiLine(spriteBatch, label, x, y, 400, HAlignment.CENTER);
}
}
Oh, and Action is just a thingy that has an execute method and, well, represents an action.
public interface Action {
abstract void execute();
}
Feel free to ask any related question in the comments, and I'll try to clarify what's needed.
Hope this helps!
I have a JavaFX 2 table that is displaying contact details for people, lets imagine there are three columns: first name, last name and email address. When my application starts it populates the table with several rows of data about the people already in the system.
The problem is that the column widths are all the same. Most of the time the first and last name is displayed in full but the email address is getting clipped. The user can double click the divider in the header to resize the column but that will become tedious quickly.
Once the table has been pre-populated I would like to programatically resize all the columns to display the data they contain but I can't figure out how to achieve this. I can see that I can call col.setPrefWidth(x) but that doesn't really help as I would have to guess the width.
If your total number of columns are pre-known. You can distribute the column widths among the tableview's width:
nameCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
surnameCol.prefWidthProperty().bind(personTable.widthProperty().divide(2)); // w * 1/2
emailCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
In this code, the width proportions of columns are kept in sync when the tableview is resized, so you don't need to do it manually. Also the surnameCol takes the half space of the tableview's width.
This works for me in JavaFX 8
table.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY );
col1.setMaxWidth( 1f * Integer.MAX_VALUE * 50 ); // 50% width
col2.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
col3.setMaxWidth( 1f * Integer.MAX_VALUE * 20 ); // 20% width
In the other examples you have the problem, the vertical scrollbar width is ignored.
As I use SceneBuider, I just define the MinWidth, and MaxWidth to some columns and to the main column I just define the PrefWidth to "USE_COMPUTED_SIZE"
After 3 years, finally I found the solution, javafx column in tableview auto fit size
import com.sun.javafx.scene.control.skin.TableViewSkin;
import javafx.scene.control.Skin;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class GUIUtils {
private static Method columnToFitMethod;
static {
try {
columnToFitMethod = TableViewSkin.class.getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
columnToFitMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public static void autoFitTable(TableView tableView) {
tableView.getItems().addListener(new ListChangeListener<Object>() {
#Override
public void onChanged(Change<?> c) {
for (Object column : tableView.getColumns()) {
try {
columnToFitMethod.invoke(tableView.getSkin(), column, -1);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
});
}
}
If you had 4 columns and only last column needed to expand to fill the rest of the table width and the other columns remained the size I set in Scene Builder.
double width = col1.widthProperty().get();
width += col2.widthProperty().get();
width += col3.widthProperty().get();
col4.prefWidthProperty().bind(table.widthProperty().subtract(width));
Or if you had 2 columns that needed to expand then.
double width = col1.widthProperty().get();
width += col3.widthProperty().get();
col2.prefWidthProperty().bind(table.widthProperty().subtract(width).divide(2));
col4.prefWidthProperty().bind(table.widthProperty().subtract(width).divide(2));
Also, a very simple trick based on an AnchorPane will be a good solution.
We gonna wrap the TableView into a AnchorPane but also we gonna anchor the left and right side of the TableView like this:
AnchorPane wrapper = new AnchorPane();
AnchorPane.setRightAnchor(table, 10.0);
AnchorPane.setLeftAnchor(table, 10.0);
wrapper.getChildren().add(table);
This simple code will stretch the TableView in both directions (right and left) also, it will adjust whenever the scrollbar is added.
You can get an idea of how this works watching this animated gif.
Now you can resize the columns, adding these lines:
fnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
lnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 40 ); // 40% width
emColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
my idea.
table.getColumns().add(new TableColumn<>("Num") {
{
// 15%
prefWidthProperty().bind(table.widthProperty().multiply(0.15));
}
});
table.getColumns().add(new TableColumn<>("Filename") {{
// 20%
prefWidthProperty().bind(table.widthProperty().multiply(.2));
}});
table.getColumns().add(new TableColumn<>("Path") {{
// 50%
prefWidthProperty().bind(table.widthProperty().multiply(.5));
}});
table.getColumns().add(new TableColumn<>("Status") {
{
// 15%
prefWidthProperty().bind(table.widthProperty().multiply(.15));
}
});
I'm using the ShowTextAtPoint method of CGContext to display a Text in a view, but it is displayed in flip mode, anyone knows how to solve this problem ?
Here is the code I use :
ctx.SelectFont("Arial", 16f, CGTextEncoding.MacRoman);
ctx.SetRGBFillColor(0f, 0f, 1f, 1f);
ctx.SetTextDrawingMode(CGTextDrawingMode.Fill);
ctx.ShowTextAtPoint(centerX, centerY, text);
You can manipulate the current transformation matrix on the graphics context to flip it using ScaleCTM and TranslateCTM.
According to the Quartz 2D Programming Guide - Text:
In iOS, you must apply a transform to the current graphics context in order for the text to be oriented as shown in Figure 16-1. This transform inverts the y-axis and translates the origin point to the bottom of the screen. Listing 16-2 shows you how to apply such transformations in the drawRect: method of an iOS view. This method then calls the same MyDrawText method from Listing 16-1 to achieve the same results.
The way this looks in MonoTouch:
public void DrawText(string text, float x, float y)
{
// the incomming coordinates are origin top left
y = Bounds.Height-y;
// push context
CGContext c = UIGraphics.GetCurrentContext();
c.SaveState();
// This technique requires inversion of the screen coordinates
// for ShowTextAtPoint
c.TranslateCTM(0, Bounds.Height);
c.ScaleCTM(1,-1);
// for debug purposes, draw crosshairs at the proper location
DrawMarker(x,y);
// Set the font drawing parameters
c.SelectFont("Helvetica-Bold", 12.0f, CGTextEncoding.MacRoman);
c.SetTextDrawingMode(CGTextDrawingMode.Fill);
c.SetFillColor(1,1,1,1);
// Draw the text
c.ShowTextAtPoint( x, y, text );
// Restore context
c.RestoreState();
}
A small utility function to draw crosshairs at the desired point:
public void DrawMarker(float x, float y)
{
float SZ = 20;
CGContext c = UIGraphics.GetCurrentContext();
c.BeginPath();
c.AddLines( new [] { new PointF(x-SZ,y), new PointF(x+SZ,y) });
c.AddLines( new [] { new PointF(x,y-SZ), new PointF(x,y+SZ) });
c.StrokePath();
}