How do I create and distribute diagonal stripes on a rectangle? - swing

I would like to be able to create bar charts with JFreeChart that looks similar to the following picture.
It is a very basic mono-colored bar chart, but with one "fancy" detail: the diagonal stripes. I was thinking that this could be made possible by overlaying another picture on top of the normal bar. This picture would have the same dimensions as the bar, have diagonal white stripes and a transparent background. I am not quite sure how to do this though, as I have very little GUI experience, but I found a very useful article that deals with overlaying images on top of graphics from JFreeChart, so I am quite certain I should be able to pull that of.
But how should I create the diagonal stripes?
I see how I could distribute the lines from the lower left corner to the upper right corner, but not the capped lines in the upper left and lower right corner. Can I somehow paint outside the rectangle (and not have it included in the picture)?
edit: After some searching I cannot see that my suggestion of overlaying an image with a transparent background would work, as I cannot find any examples on how to do this. On the other hand, merely painting the lines on the rectangle is probably easier.

Using a gradient fill to draw lines
On trashgod's tip I tried filling a shape with a gradient that had sharp edges to simulate line drawing. This would prevent a lot of calculations and could potentially be a lot simpler. It worked quite ok for thick lines, but not for thinner lines. Using the following code produces the fill in the first picture:
rect.setSpace(spaceBetweenLines);
Color bg = Color.YELLOW;
Color fg = Color.BLUE;
rect.setPaint(new LinearGradientPaint(
(float) startX, (float) startY, (float) (startX + spaceBetweenLines), (float) (startY + spaceBetweenLines),
new float[] {0,.1f,.1001f}, new Color[] {fg,fg,bg}, MultipleGradientPaint.CycleMethod.REPEAT)
);
Drawing lines using graphic primitives
Although simpler it did not work in my case. The more elaborate, but to me, more natural way of doing it, is simply drawing lines on top of the shape (rectangle, cirle, ...). The following code was used in producing the second image. Observe the use of the clip(Shape s) to restrict the line drawing to the shape underneath. The reason for not simply drawing a rectangle and using clip() to limit the shape is that the clip() operation is not aliased, thus producing jaggies. Therefore I have to draw the shape first to get smooth edges, then set the clip to prevent overflow in the forthcoming line drawing, and finally draw the lines.
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fill(getShape());
g2.setClip(getShape());
// draw diagonal lines
g2.setPaint(getLineColor());
for (int x = (int) this.x, y = (int) (this.y); y - height < (this.y + height + getSpace()); ) {
g2.drawLine(x, y , x + (int) width , y - (int) width);
y += getSpace();
}

The source code for BarChartDemo1 shows how to apply a GradientPaint, but you may want to experiment with LinearGradientPaint to get the diagonal effect.
I want to paint the bars, not the background.
If you already have a suitable image, TexturePaint may be an alternative.

Related

How to implement rotating rectangle around circle in libGDX Box2D?

I want to implement rotating rectangle around cicrle in such way, that circle has no rotation, and rectangle has. All object's are Box2D Body objects. Here is picture, what I want to have:
In my case rectangle touches circle, but I think it doesn't matter.
At first I tried to do it with two Fictures for same Body, but there was a problem with rotation: I couldn't have one ficture with rotation and another without.
I think, it should be somehow connected with joints, but I don't know what exactly Joint I should use. Maybe are there another solutions?
I think DistanceJointDef will do the tricks
you could put the radius if the circle as the distance with a little margin if you want
you also have to reduce the friction of bodies so the rectangle can move smoothly
DistanceJointDef djd = new DistanceJointDef();
djd.bodyA = bodyRactangle;
djd.bodyB = bodyCirlce;
djd.length = radius + margin;
world.createJoint(djd);
bodyRactangle is a dynamic body
bodyCirlce is a static body
try that for a start, hope it is helpful
Good luck !!

Scale, Position & Rotate Parent object to make child object take up entire stage

Using the first photo below, let's say:
The red outline is the stage bounds
The gray box is a Sprite on the stage.
The green box is a child of the gray box and has a rotation set.
both display object are anchored at the top-left corner (0,0).
I'd like to rotate, scale, and position the gray box, so the green box fills the stage bounds (the green box and stage have the same aspect ratio).
I can negate the rotation easily enough
parent.rotation = -child.rotation
But the scale and position are proving tricky (because of the rotation). I could use some assistance with the Math involved to calculate the scale and position.
This is what I had tried but didn't produce the results I expected:
gray.scaleX = stage.stageWidth / green.width;
gray.scaleY = gray.scaleX;
gray.x = -green.x;
gray.y = -green.y;
gray.rotation = -green.rotation;
I'm not terribly experienced with Transformation matrices but assume I will need to go that route.
Here is an .fla sample what I'm working with:
SampleFile
You can use this answer: https://stackoverflow.com/a/15789937/1627055 to get some basics. First, you are in need to rotate around the top left corner of the green rectangle, so you use green.x and green.y as center point coordinates. But in between you also need to scale the gray rectangle so that the green rectangle's dimensions get equal to stage. With uniform scaling you don't have to worry about distortion, because if a gray rectangle is scaled uniformly, then a green rectangle will remain a rectangle. If the green rectangle's aspect ratio will be different than what you want it to be, you'd better scale the green rectangle prior to performing this trick. So, you need to first transpose the matrix to offset the center point, then you need to add rotation and scale, then you need to transpose it away. Try this set of code:
var green:Sprite; // your green rect. The code is executed within gray rect
var gr:Number=green.rotation*Math.PI/180; // radians
var gs:Number=stage.stageWidth/green.width; // get scale ratio
var alreadyTurned:Boolean; // if we have already applied the rotation+scale
function turn():void {
if (alreadyTurned) return;
var mat:flash.geom.Matrix=this.transform.matrix;
mat.scale(gs,gs);
mat.translate(-gs*green.x,-gs*green.y);
mat.rotate(-1*gr);
this.transform.matrix=mat;
alreadyTurned=true;
}
Sorry, didn't have time to test, so errors might exist. If yes, try swapping scale, translate and rotate, you pretty much need this set of operations to make it work.
For posterity, here is what I ended up using. I create a sprite/movieClip inside the child (green) box and gave it an instance name of "innerObj" (making it the actually content).
var tmpRectangle:Rectangle = new Rectangle(greenChild.x, greenChild.y, greenChild.innerObj.width * greenChild.scaleX, greenChild.innerObj.height * greenChild.scaleY);
//temporary reset
grayParent.transform.matrix = new Matrix();
var gs:Number=stage.stageHeight/(tmpRectangle.height); // get scale ratio
var mat:Matrix=grayParent.transform.matrix;
mat.scale(gs,gs);
mat.translate(-gs * tmpRectangle.x, -gs * tmpRectangle.y);
mat.rotate( -greenChild.rotation * Math.PI / 180);
grayParent.transform.matrix = mat;
If the registration point of the green box is at one of it's corners (let's say top left), and in order to be displayed this way it has a rotation increased, then the solution is very simple: apply this rotation with negative sign to the parent (if it's 56, add -56 to parent's). This way the child will be with rotation 0 and parent -> -56;
But if there is no rotation applied to the green box, there is almost no solution to your problem, because of wrong registration point. There is no true way to actually determine if the box is somehow rotated or not. And this is why - imagine you have rotated the green box at 90 degrees, but changed it's registration point and thus it has no property for rotation. How could the script understand that this is not it's normal position, but it's flipped? Even if you get the bounds, you will see that it's a regular rectangle, but nobody know which side is it's regular positioned one.
So the short answer is - make the registration point properly, and use rotation in order to display it like in the first image. Then add negative rotation to the parent, and its all good :)
Edit:
I'm uploading an image so I can explain my idea better:
 
As you can see, I've created a green object inside the grey one, and the graphics INSIDE are rotated. The green object itself, has rotation of 0, and origin point - top left.
#Vesper - I don't think that the matrix will fix anything in this situation (remember that the green object has rotation of 0).
Otherwise I agree, that the matrix will do a pretty job, but there are many ways to do it :)

Rotate the group and scribbling on the group in a stage.. postting with code

Please this fiddle I have copied my complete project in it
here if you open the fiddle in the output you can see an image, scribble on the image selecting pen,add text etc(like this perform some functions).then rotate the group using rotate button and then try to scribble you will understand what is the problem exactly.
In me view Problem is I am having a stage and a layer is added to the stage and a group is added to the layer and different elements like lines text etc are added to the group. then group is rotated the i am trying to draw the line based on the mouse position of the stage.But it is not coming correctly because the group got rotated the x and y what we are taking to draw a line is from stage.I need to take the x and y from the group not from the stage is their any way.If hav't understand please ask me or post a reply.
This should get you fairly close: http://jsfiddle.net/k4qB8/24/
// This rotates that added active line along with your group.
// This makes the draw direction correct
activeline.setRotationDeg(0-rootGroup.getRotationDeg());
// Here you'll have to figure a way to calculate how much to move the
// line over so the draw is on the correct spot
// This is as close as I got it
if(Math.abs(rootGroup.getRotationDeg()%360)==0)
activeline.move(rootGroup.getX()-375, rootGroup.getY()-175);
if(Math.abs(rootGroup.getRotationDeg()%360)==90)
activeline.move(rootGroup.getX()-175, rootGroup.getY()+375);
if(Math.abs(rootGroup.getRotationDeg()%360)==180)
activeline.move(rootGroup.getX()+375, rootGroup.getY()+175);
if(Math.abs(rootGroup.getRotationDeg()%360)==270)
activeline.move(rootGroup.getX()+175, rootGroup.getY()-375);
Also, add some more logic for counter-clockwise rotation, as this doesn't work 100%.
I think the real solution would be to just draw on separate layers for each rotation, kind of like this:
if (rotation is 90) : draw on lineLayer1;
if (rotation is 180) : draw on lineLayer2;
if (rotation is 270) : draw on lineLayer3;
if (rotation is 360 || 0) : draw on lineLayer4;
This way you could just rotate the layers which are not drawn on to simulate the feel of rotation.

How can I created a curved health bar?

I'm making a game with a health bar and I am trying to make a health bar that is curved.
Currently I have a lineBar that has 20 segments that looks like this at the bottom left of the screen.
What I'd like to do is write a function that goes through and modifies the scaleY of each to get a curved bar.
I can easily scale them down in a straight line. So that it looks triangle ish.
I want exponential decay.
In normal math terms it might be something like y = Pa^x.
I developed a game with a curved health bar a while back, this is how I achieved it:
Step 1:
Create your curved bar. I suggest the Oval Primitive tool:
Draw your bar. I suggest creating a guide layer to demonstrate a whole-circle visual of your curved segment. Copy the bar onto another layer and make it a mask, this will be what reveals your healthbar. The mask and the segment should be MovieClips:
Step 2:
Set the registration point of your mask to the centre of your guide circle. Your mask will rotate around this point to reveal your actual bar. Rotate your mask so that it is to the left of your actual bar graphic:
Step 3:
Create a tween of your mask rotating clockwise across 100 frames (add more frames for finer progression). You can even apply a tween to your bar graphics where the colour changes from red to green as it fills, etc.
Step 4:
Use gotoAndStop() on this element to determine which frame you should stop on throughout the animation. The formula I use here is generally:
gotoAndStop( Math.round( currentHealth / maxHealth * x ) );
Where x is the amount of frames you created.
Hope this helps.

understanding matrix.transition(); as3

I am trying to understand the method transition that falls in the Matrix Class. I am using it to copy pieces of a bitMapData. But I need to better understand what transitions do.
I have a tilesheet that has 3 images on it. all 30x30 pixels. the width of the total bitmap is 90pxs.
The first tile is green, the second is brown, and the third is yellow. If I move over 30pxs using the matrix that transitions, instead of getting brown, I get yellow, if I move over 60px, I get brown.
If I move -30 pixels, then the order is correct. I am confused on what is going on.
tileNum -= (tileNumber * tWidth);
theMatrix = new Matrix();
theMatrix.translate(tileNum,0);
this.graphics.beginBitmapFill(tileImage,theMatrix);
this.graphics.drawRect(0, 0,tWidth ,tHeight );
this.graphics.endFill();
Can someone tell me how transitions work, or some resources that show how they work. I ultimately want to know a good way to switch back and forth between each tile.
First of all, don't confuse translation with transition. The latter is a general English word for "change", whereas to translate in geometry and general math is to "move" or "offset" something.
A transformation matrix defines how to transform, i.e. scale, rotate and translate, an object, usually in a visual manner. By applying a transformation matrix to an object, all pixels of that object are rotated, moved and scaled/interpolated according to the values stored inside the matrix. If you'd rather not think about matrix math, just think of the matrix as a black box which contains a sequence of rotation, scaling, and translation commands.
The translate() method simply offsets the bitmap that you are about to draw a number of pixels in the X and Y dimensions. If you use the default ("identity") matrix, which contains no translation, the top left corner of your object/bitmap will be in the (0,0) position, known as the origin or registration point.
Consider the following matrix:
var mtx : Matrix = new Matrix; // No translation, no scale, no rotation
mtx.translate(100, 0); // translated 100px on X axis
If you use the above matrix with a BitmapData.draw() or Graphics.beginBitmapFill(), that means that the top left corner of the original bitmap should be at (x=100; y=0) in the target coordinate system. Sticking to your Graphics example, lets first consider drawing a rectangle without a matrix transformation.
var shape : Shape = new Shape;
shape.graphics.beginBitmapFill(myBitmap);
shape.graphics.drawRect(0, 0, 200, 200);
This will draw a 200x200 pixels rectangle. Since there is no transformation involved in the drawing method (we're not supplying a transformation matrix), the top left corner of the bitmap is in (x=0; y=0) of the shape coordinate system, i.e. aligned with the top left corner of the rectangle.
Lets look at a similar example using the matrix.
var shape : Shape = new Shape;
shape.graphics.beginBitmapFill(myBitmap, mtx);
shape.graphics.drawRect(0, 0, 200, 200);
This again draws a rectangle that is 200px wide and 200px high. But where inside this rectangle will the top left corner of myBitmap be? The answer is at (x=100, y=0) of the shape coordinate system. This is because the matrix defines such a translation.
But what then will be to the left of (x=100; y=0)? With the above code, the answer is that the bitmap repeats to fill the entire rectangle, and hence you will see the rightmost side of the bitmap, to the left of the leftmost side, as if there was another instance of the bitmap right next to it. If you want to disable the repeating image, set the third attribute of beginBitmapFill() to false:
shape.graphics.beginBitmpFill(myBitmap, mtx, false);
Lets take a look at one last example that might help your understanding. Remember that the translation matrix defines the position of the top left corner of an image, in the coordinate system of the shape. With this in mind, consider the following code, using the same matrix as before.
var shape : Shape = new Shape;
shape.graphics.beginBitmapFill(myBitmap, mtx);
shape.graphics.drawRect(100, 0, 100, 100);
Notice that this will draw the rectangle 100px in on the X axis. Not coincidentally, this is the same translation that we defined in our matrix, and hence the position of the top left corner of the bitmap. So even though repeating is enabled, we will not see a repeating image to the left of our rectangle, because we only start drawing at the point where the bitmap starts.
So the bottom line is, I guess, that you could think of the transform matrix as a series of transformation commands that you apply to your image as you draw it. This will offset, scale and rotate the image as it's drawn.
If you are curious about the inner workings of the matrix, Google transformation matrices, or read up on Linear Algebra!