I cannot get it working although I am very close to an acceptable solution.
I can drag the Dock if it is only a rectangle. But if I add a node (e.g. an image) to this dock I am not able to get a working solution.
Here is my code:
public class Dock extends CustomNode {
// initialize this with an 64x64 image of your choice
// via ImageView { image: Image {..}}
public var content: Node[];
public var width = 64;
public var height = 64;
public var xOffset: Number = 0;
public var yOffset: Number = 0;
var imgX: Number = 0;
var imgY: Number = 0;
var distX: Number;
var distY: Number;
public var rasterX = function (n: Number): Number {
var MAX = 4 * 64;
if (n < 0) {
return 0
} else if (n > MAX) {
return MAX
} else
return n
}
public var rasterY = rasterX;
override protected function create(): Node {
Group {
// if we place the translate here then the whole dock will flicker
//translateX: bind imgX;
//translateY: bind imgY;
content: [
Rectangle {
// ... and here 'content' logically won't be dragged
translateX: bind imgX;
translateY: bind imgY;
height: bind height
width: bind width
fill: Color.LIGHTGRAY
strokeWidth: 4
stroke: Color.BLACK
}, content]
onMousePressed: function (e: MouseEvent): Void {
xOffset = e.x;
yOffset = e.y;
// Calculate the distance of the mouse point from the image
// top-left corner which will always come out as positive value
distX = e.x - imgX;
distY = e.y - imgY;
}
onMouseDragged: function (e: MouseEvent): Void {
// Find out the new image postion by subtracting the distance
// part from the mouse point.
imgX = rasterX(e.x - distX);
imgY = rasterY(e.y - distY);
}
}
}
I tried blocksMouse:true on different nodes, tried it with mouseReleased etc but I coudn't get properly working solution. Do you have any pointers/tips on how this it done correctly?
Finally sorted it out from this example, but you don't need to follow the tutorial (I got an exception!?) - simply download the sources or use:
public class Dock extends CustomNode {
public var content: Node[];
public var width = 64;
public var height = 64;
public var xOffset: Number = 0;
public var yOffset: Number = 0;
public var rasterX = function (n: Number): Number {
// the following code is for the 'grid' which can be avoided of course
var n2 = n - n mod 64;
var MAX = 4 * 64;
if (n2 < 0) {
return 0
} else if (n2 > MAX) {
return MAX
} else
return n2
}
public var rasterY = rasterX;
override protected function create(): Node {
var node: Group;
node = Group {
content: [
Rectangle {
height: bind height
width: bind width
arcHeight: 10
arcWidth: 10
fill: Color.LIGHTGRAY
strokeWidth: 4
stroke: Color.BLACK
effect: DropShadow {
offsetX: 5
offsetY: 5
color: Color.DARKGRAY
radius: 10
}
}, content]
onMousePressed: function (e: MouseEvent): Void {
xOffset = e.sceneX - node.translateX;
yOffset = e.sceneY - node.translateY;
}
onMouseDragged: function (e: MouseEvent): Void {
node.translateX = rasterX(e.sceneX - yOffset);
node.translateY = rasterY(e.sceneY - yOffset);
}
}
}
}
Related
I am customizing Badge in TabbedPage. I have now added the red dot from inheriting UIView. However how can I Add Text inside that Frame. Xamarin iOS
MyTabbedPageRenderer.cs
public static class TabbarExtensions
{
readonly static int tabBarItemTag = 9999;
public static void addItemBadge(this UITabBar tabbar, int index)
{
if (tabbar.Items != null && tabbar.Items.Length == 0) return;
if (index >= tabbar.Items.Length) return;
removeItemBadge(tabbar, index);
var badgeView = new UIView();
badgeView.Tag = tabBarItemTag + index;
badgeView.Layer.CornerRadius = 7;
badgeView.BackgroundColor = UIColor.Red;
var tabFrame = tabbar.Frame;
var percentX = (index + 0.56) / tabbar.Items.Length;
var x = percentX * tabFrame.Width;
var y = tabFrame.Height * 0.05;
badgeView.Frame = new CoreGraphics.CGRect(x, y, 13, 13);
tabbar.AddSubview(badgeView);
//var badgeView = new UILabel();
//badgeView.Tag = tabBarItemTag + index;
//badgeView.BackgroundColor = UIColor.Red;
//var tabFrame = tabbar.Frame;
//var percentX = (index + 0.56) / tabbar.Items.Length;
//var x = percentX * tabFrame.Width;
//var y = tabFrame.Height * 0.05;
//badgeView.Text = "1";
//badgeView.TextAlignment = UITextAlignment.Center;
//badgeView.TextColor = UIColor.White;
//badgeView.Font = UIFont.SystemFontOfSize(10);
//tabbar.AddSubview(badgeView);
}
public static bool removeItemBadge(this UITabBar tabbar, int index)
{
foreach (var subView in tabbar.Subviews)
{
if (subView.Tag == tabBarItemTag + index)
{
subView.RemoveFromSuperview();
return true;
}
}
return false;
}
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
MessagingCenter.Subscribe<object, int>(this, "Add", (obj, index) => {
TabBar.addItemBadge(index);
});
MessagingCenter.Subscribe<object, int>(this, "Remove", (obj, index) => {
TabBar.removeItemBadge(index);
});
}
MainView.xaml.cs
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<object, int>(this, "Add", 2);
}
As in my code above I tried with UILabel. However I cannot set CornerRadius for Label
Summarize how I can Add Text inside Frame. Or how can I set CornerRadius for Lable in Xamarin iOS.
Thank you!
Description picture:
If I use UILabel, I cannot set CornerRadius
If I use UIView
For UILabel, you could set the CornerRadius using the following:
badgeView.Layer.CornerRadius = 7;
badgeView.Layer.MasksToBounds = true;//add this line
For more info, you could refer to masksToBounds.
Hope it works for you.
I beg you to help me. I'm creating a small chart and it's not working make the connecting lines between the rectangles so that they stretch
after moving the rectangle-nodes. What we have:
3 rectangles created in OOR js svg;
created connecting lines with rectangles (in OOP js svg);
function for moving rectangle-nodes.
What is the problem. When dragging nodes, the lines break away from the rectangles.
An example of how a diagram works
here
I ask for help in creating a function for updating the line when dragging the nodes of the diagram.
I think that it needs to put the value of the points of contact, put the name of the update function
to the code of the drag/drop function
created the updateLines() function;
inserted conn1.x1 into it; conn.y1;conn1.x2;conn1.y2;
inserted into it var connect1 = new Lines();
connect1.draw();
varx3 = rec3.location.x+100; var y3 = rec3.location.y; /////
var connect2 = new Lines(rec1.location.x+100,rec1.location.y+80, rec3.location.x+100, rec3.location.y,stroke='green',id='l2');
connect2.draw();
I inserted the name of the function into the makeDraggable(evt) code;
<style>
.background {
fill: #eee;
}
.static {
cursor: not-allowed;
}
.draggable {
cursor: move;
}
</style>
-----------------------
<svg xmlns="http://www.w3.org/2000/svg" id="forDraw" viewBox="0 0 1330 420" onload="makeDraggable(evt)">
</svg>
------------------
function makeDraggable(evt) {
var svg = evt.target;
svg.addEventListener('mousedown', startDrag);
svg.addEventListener('mousemove', drag);
svg.addEventListener('mouseup', endDrag);
function getMousePosition(evt) {
var CTM = svg.getScreenCTM();
return {
x: (evt.clientX - CTM.e) / CTM.a,
y: (evt.clientY - CTM.f) / CTM.d
};
}
var selectedElement, offset;
function startDrag(evt) {
if (evt.target.classList.contains('draggable')) {
selectedElement = evt.target;
offset = getMousePosition(evt);
offset.x -= parseFloat(selectedElement.getAttributeNS(null, "x"));
offset.y -= parseFloat(selectedElement.getAttributeNS(null, "y"));
}
}
function drag(evt) {
if (selectedElement) {
var coord = getMousePosition(evt);
selectedElement.setAttributeNS(null, "x", coord.x - offset.x);
selectedElement.setAttributeNS(null, "y", coord.y - offset.y);
}
}
function endDrag(evt) {
selectedElement = null;
}
}
var recWidth = '200';
var recHeight = '80';
function Rectangle(width,height, location={x: 400, y: 50},style='draggable', fill = 'red', stroke = 'green',id='ivan') {
this.width = recWidth;
this.height = recHeight;
this.location = location;
this.style = style;
this.fill = fill;
this.stroke = stroke;
this.id = id;
this.draw = function() {
forDraw.innerHTML += `<rect width="${this.width}" height="${this.height}" x="${this.location.x}" y="${this.location.y}"
class="${this.style}" fill="${this.fill}" stroke="${this.stroke}" id="${this.id}" />`;
}
}
Rectangle.prototype.draw = function() {
if (forDraw.getElementById(this.id)) forDraw.getElementById(this.id).remove();
forDraw.innerHTML += `<rect width="${this.width}" height="${this.height}" x="${this.location.x}" y="${this.location.y}"
class="${this.style}" fill="${this.fill}" stroke="${this.stroke}" id="${this.id}" />`;
}
var rec1 = new Rectangle();
rec1.draw();
var rec2 = new Rectangle(150,90, {x: 300, y:300}, style='draggable','yellow', 'red','petro');
rec2.draw();
var rec3 = new Rectangle(150,90, {x: 550, y:300}, style='draggable','green', 'blue','dima');
rec3.draw();
function Lines(x1=rec1.location.x+100, y1=rec1.location.y+80, x2=rec2.location.x+100, y2=rec2.location.y, stroke='blue',id='l1') {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.stroke = stroke;
this.id = id;
this.draw = function() {
forDraw.innerHTML += `<line x1="${this.x1}" y1="${this.y1}" x2="${this.x2}" y2="${this.y2}"
stroke="${this.stroke}" id="${this.id}" />`;
}
}
var connect1 = new Lines();
connect1.draw();
var x3 = rec3.location.x+100;
var y3 = rec3.location.y;
/////
var connect2 = new Lines(rec1.location.x+100,rec1.location.y+80, rec3.location.x+100, rec3.location.y,stroke='green',id='l2');
connect2.draw();
I made a test game in unity that makes it so when I click on a button, it spawns a cylinder created from a factory class. I'm trying to make it so when I create the cylinder, its height shrinks over the next 20 seconds. Some methods I found are difficult to translate into what I'm doing. If you could lead me to the right direction, I'd very much appreciate it.
Here's my code for the cylinder class
public class Cylinder : Shape
{
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.transform.localScale = new Vector3(1.0f, Random.Range(1, 2)-1*Time.deltaTime, 1.0f);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
}
This can be done with the Time.deltaTime and Vector3.Lerp in a coroutine function. Similar to Rotate GameObject over time and Move GameObject over time questions. Modified it a little bit to do just this.
bool isScaling = false;
IEnumerator scaleOverTime(Transform objectToScale, Vector3 toScale, float duration)
{
//Make sure there is only one instance of this function running
if (isScaling)
{
yield break; ///exit if this is still running
}
isScaling = true;
float counter = 0;
//Get the current scale of the object to be moved
Vector3 startScaleSize = objectToScale.localScale;
while (counter < duration)
{
counter += Time.deltaTime;
objectToScale.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
isScaling = false;
}
USAGE:
Will scale GameObject within 20 seconds:
StartCoroutine(scaleOverTime(cylinder.transform, new Vector3(0, 0, 90), 20f));
Check out Lerp. A general example of how to use it would be something like this:
float t = 0;
Update()
{
t += Time.deltaTime;
cylinder.localScale = new Vector3(1, Mathf.Lerp(2f, 1f, t/3f), 1); // shrink from 2 to 1 over 3 seconds;
}
You will create a new monobehaviour script and add it to your primitive. Then you wil use "Update" method of monobehaviour (or use coroutine) for change object over time.
Monobehaviour must be look like this:
public class ShrinkBehaviour : MonoBehaviour
{
bool isNeedToShrink;
Config currentConfig;
float startTime;
float totalDistance;
public void StartShrink(Config config)
{
startTime = Time.time;
currentConfig = config;
totalDistance = Vector3.Distance(currentConfig.startSize, currentConfig.destinationSize);
isNeedToShrink = true;
transform.localScale = config.startSize;
}
private void Update()
{
if (isNeedToShrink)
{
var nextSize = GetNextSize(currentConfig);
if (Vector3.Distance(nextSize, currentConfig.destinationSize) <= 0.05f)
{
isNeedToShrink = false;
return;
}
transform.localScale = nextSize;
}
}
Vector3 GetNextSize(Config config)
{
float timeCovered = (Time.time - startTime) / config.duration;
var result = Vector3.Lerp(config.startSize, config.destinationSize, timeCovered);
return result;
}
public struct Config
{
public float duration;
public Vector3 startSize;
public Vector3 destinationSize;
}
}
For using this, you must do next:
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
var shrink = cylinder.AddComponent<ShrinkBehaviour>();
shrink.StartShrink(new ShrinkBehaviour.Config() { startSize = Vector3.one * 10, destinationSize = Vector3.one * 1, duration = 20f });
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
You must remember, monobehaviour-script must be in separate file, and must have name similar to monobehaviour-class name. For example, ShrinkBehaviour.cs;
I'm working on a blackberry project and for that I need to create grid layout. I'm working on "Blackberry java sdk".
I'm using this code
public class GridScreen extends UiApplication {
// main method
public static void main(String[] args) {
GridScreen theApp = new GridScreen();
UiApplication.getUiApplication().pushScreen(new GFMScreen());
theApp.enterEventDispatcher();
}
}
// VFM
class GFMScreen extends MainScreen {
public GFMScreen() {
// this doesnt do anything for VCENTER!!
//super(Field.USE_ALL_HEIGHT);
// create a grid field manager, with 2 cols and 0 style param for super class
// style of Manager.FIELD_VCENTER | Field.USE_ALL_HEIGHT doesnt do a thing!
int columns = 2;
final GridFieldManager gfm = new GridFieldManager(columns, 0);
// add some items to the screen
int size = 6;
BitmapField[] fRay = new BitmapField[size];
for (int i = 0; i < size; i++) {
// create an bitmap field that's centered H + V (inside grid space)
fRay[i] = new BitmapField(loadBitmap("images/" + (i + 1) + ".png"),
Field.FIELD_HCENTER | Field.FIELD_VCENTER | Field.FOCUSABLE);
gfm.add(fRay[i]);
}
// set padding on top/bottom
{
// add gfm to screen - this does not center the gfm on the screen... is top aligned no matter what!
add(gfm);
int gfmHeight = 48 * (size / columns);
int borderHeight = (Display.getHeight() - gfmHeight) / 2;
gfm.setBorder(BorderFactory.createSimpleBorder(
new XYEdges(borderHeight, 0, borderHeight, 0),
Border.STYLE_TRANSPARENT));
System.out.println("border=" + borderHeight);
System.out.println("display=" + Display.getHeight());
System.out.println("gfm=" + gfmHeight);
}
}
/** #param res eg "images/icon.png" */
public static Bitmap loadBitmap(String res) {
EncodedImage img = EncodedImage.getEncodedImageResource(res);
return img.getBitmap();
}
}// end class
What is wrong in this code?
Is there any best approch to create grid layout in BlackBerry.
In above code error is "Display.getHeight() is not define".
Hope this code helps:
Bitmap[] images = new Bitmap[6];
for ((int i = 0; i < 6; i++) {
string filename = "images/" + String.valueOf(i + 1) + ".png";
images[i] = Bitmap.getBitmapResource(filename);
}
}
Is there any way to create a Tab Menu in j2me?
I found a code but I am unable to understand it
In this code there is Tab Menu created which is in Canvas class and then Tab menu is created which is totally done in Canvas or painted. The only part I found difficult to grasp was the void go() method and then
When I try to draw anything above and below this code using paint method, it doesn't work - what's the problem?
Below is the code
// Tab Menu CANVAS class
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class TabMenuCanvas extends Canvas
{
TabMenu menu = null;
public TabMenuCanvas()
{
menu = new TabMenu(
new String[]{"Home", "News", "Community", "Your files", "Credits", "Events", "Blog", "Upload", "Forum Nokia"},
getWidth() - 20
);
}
protected void keyPressed(int key)
{
int gameAction = getGameAction(key);
if(gameAction == Canvas.RIGHT)
{
menu.goRight();
repaint();
}
else if(gameAction == Canvas.LEFT)
{
menu.goLeft();
repaint();
}
}
protected void paint(Graphics g)
{
g.translate(10, 30);
menu.paint(g);
g.translate(- 10, - 30);
}
}
// Tab Menu Class
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TabMenu
{
int background = 0xffffff;
int bgColor = 0xcccccc;
int bgFocusedColor = 0x0000ff;
int foreColor = 0x000000;
int foreFocusedColor = 0xffffff;
int cornerRadius = 6;
int padding = 2;
int margin = 2;
Font font = Font.getDefaultFont();
int scrollStep = 20;
int selectedTab = 0; //selected tab index
int[] tabsWidth = null; //width of single tabs
int[] tabsLeft = null; //left X coordinate of single tabs
int tabHeight = 0; //height of tabs (equal for all tabs)
String[] tabs = null; //tab labels
int menuWidth = 0; //total menu width
int viewportWidth = 0; //visible viewport width
int viewportX = 0; //current viewport X coordinate
public TabMenu(String[] tabs, int width)
{
this.tabs = tabs;
this.viewportWidth = width;
initialize();
}
void initialize()
{
tabHeight = font.getHeight() + cornerRadius + 2 * padding; //[ same for all tabs]
menuWidth = 0;
tabsWidth = new int[tabs.length];
tabsLeft = new int[tabs.length];
for(int i = 0; i < tabsWidth.length; i++)
{
tabsWidth[i] = font.stringWidth(tabs[i]) + 2 * padding + 2 * cornerRadius;
tabsLeft[i] = menuWidth;
menuWidth += tabsWidth[i];
if(i > 0)
{
menuWidth += margin;
}
}
}
public void goRight()
{
go(+1);
}
public void goLeft()
{
go(-1);
}
private void go(int delta)
{
int newTab = Math.max(0, Math.min(tabs.length - 1, selectedTab + delta));
boolean scroll = true;
if(newTab != selectedTab && isTabVisible(newTab))
{
selectedTab = newTab;
if( (delta > 0 && tabsLeft[selectedTab] + tabsWidth[selectedTab] > viewportX + viewportWidth) ||
(delta < 0 && tabsLeft[selectedTab] < viewportX))
{
scroll = true;
}
else
{
scroll = false;
}
}
if(scroll)
{
viewportX = Math.max(0, Math.min(menuWidth - viewportWidth, viewportX + delta * scrollStep));
}
}
private boolean isTabVisible(int tabIndex)
{
return tabsLeft[tabIndex] < viewportX + viewportWidth &&
tabsLeft[tabIndex] + tabsWidth[tabIndex] >= viewportX;
}
public void paint(Graphics g)
{
int currentX = - viewportX;
g.setClip(0, 0, viewportWidth, tabHeight);
g.setColor(background);
g.fillRect(0, 0, viewportWidth, tabHeight);
for(int i = 0; i < tabs.length; i++)
{
g.setColor(i == selectedTab ? bgFocusedColor : bgColor);
g.fillRoundRect(currentX, 0, tabsWidth[i], tabHeight + cornerRadius, 2 * cornerRadius, 2 * cornerRadius);
g.setColor(i == selectedTab ? foreFocusedColor : foreColor);
g.drawString(tabs[i], currentX + cornerRadius + padding, cornerRadius + padding, Graphics.LEFT | Graphics.TOP);
currentX += tabsWidth[i] + margin;
}
}
}
When I try to draw anything above and below this code using paint method, it doesn't work
what of the paint methods you use to draw above and below? Pay attention that there are two methods named that way - first is in TabMenuCanvas, second is in TabMenu (second method is invoked from TabMenuCanvas#repaint).
whatever you would try to draw in TabMenuCanvas#paint will most likely be overwritten by setClip and fillRect when TabMenu#paint is invoked following repaint request
The only place where one can expect to be able to draw something visible seems to be in TabMenu#paint method, inside the clip area that is set there.
You can use GUI Libraries for J2ME,for example Lightweight User Interface Toolkit (LWUIT),Flemil have "tab menu".You can see list of GUI Libraries here.