can someone please explain the last two params of arcTo? - android

I'm trying to draw a rectangle with rounded corners. I have a javascript path that does this, but the javascript arcTo method takes a rectangle (to define its oval) and then one param which sets the sweep.
However, in the Android version there are three params. the rectangle oval (which I think I have defined correctly) and then the startAngle and sweepAngle (which I'm not understanding the usage of), but my arcs don't look anything like what I'm expecting when I noodle with how I'm guessing they should work.
Does anyone know of a good tutorial on this?
Specifically I'm trying to understand what would the two params look like if I was trying to draw an arc (on a clock face) from 12 - 3, and then assuming I had a line that ran down from the 3 and then needed to round the corner from 3 to 6 and so forth.
Here's my code (disregard the arc numbers in there now... that's just the latest iteration of my guessing at how this may work, having failed on the previous, more sensible attempts):
Path ctx = new Path();
ctx.moveTo(X+5,Y); //A
ctx.lineTo(X+W-5,Y);//B
ctx.arcTo(new RectF(X+W, Y, X+W, Y+5), -180, 90); //B arc
ctx.lineTo(X+W,Y+H-5); //C
ctx.arcTo(new RectF(X+W,Y+H,X+W-5,Y+H),90,180); //C arc
ctx.lineTo(X+W/2 +6,Y+H);
ctx.lineTo(X+W/2,Y+H+8);
ctx.lineTo(X+W/2-6,Y+H);
ctx.lineTo(X+5,Y+H);
ctx.arcTo(new RectF(X,Y+H,X,Y+H-5),180,270);
ctx.lineTo(X,Y+5);
ctx.arcTo(new RectF(X,Y,X+5,Y),270,0);
Paint p = new Paint();
p.setColor(0xffff00ff);
canvas.drawPath(ctx, p);
much obliged.

odd that no one piped in with an answer, once I found it (it wasn't easy to find) it was really straight forward.
So, the way it works is this:
Assuming you want to draw a rounded corner at 12 - 3 (using clock reference):
you start your path and when you need the line to arc you define a rectangle whose upper left corner is the place where your line is currently terminated and whose lower right corner is the place that you want the arc to go to, so if you imagine a square whose X,Y is 12 (on the clock) and whose X+W,Y+H is 3 that's the square you need.
Now, imagine that you have an oval in that square (in this example it's a circular oval, if you want your curve to be more oval-ish, then define your square as a rectangle), you can take any slice of that circle using the last two params of the method. The first param defines the angle where you want to start cutting. If we're using a compass, 0 degrees is East (not sure why, I'm not a geometry expert... is this normal? I always think of 0 being North, but all the programming geometry examples I see have 0 as East, maybe someone will comment on why that is).
The second param defines how much of the circle you want. If you want the whole circle you put 360 if you want half the circle you put 180 etc.
So, in our case since we want to round the corner from 12 to 3, we put 270 as our starting degree and grab 90 degrees of the circle.
Lastly, when you're done with this process, the line now thinks of itself as being at 3pm so you can continue lineTo(ing) from there.
So... here's my fixed code for my shape (it has a little triangle in it, but that's neither here nor there, the actual rounded parts are B-C, D-E, I-J, and K-A. All the rest are straight lines.
int arc = 25;
public Cursor(int X, int Y, int W, int H){
/*
* A B
* K C
* J D
* I H F E
G
*/
int Ax = X+ arc;
int Ay = Y;
int Bx = X + W - arc;
int By = Y;
int Cx = X + W;
int Cy = Y + arc;
int Dx = Cx;
int Dy = (Y + arc) + (H - arc*2);
int Ex = Bx;
int Ey = Y + H;
int Fx = X+W/2 +6;
int Fy = Ey;
int Gx = X+W/2;
int Gy = Y+H+8;
int Hx = X+W/2-6;
int Hy = Ey;
int Ix = Ax;
int Iy = Hy;
int Jx = X;
int Jy = Dy;
int Kx = X;
int Ky = Cy;
Path ctx = new Path();
ctx.moveTo(Ax,Ay); //A
ctx.lineTo(Bx,By);//B
ctx.arcTo(new RectF(Bx, By, Cx, Cy), 270, 90); //B-C arc
ctx.lineTo(Dx,Dy); //D
ctx.arcTo(new RectF(Dx - arc, Dy, Ex + arc, Ey),0,90); //D-E arc
ctx.lineTo(Fx, Fy); //E-F
ctx.lineTo(Gx, Gy); //F-G
ctx.lineTo(Hx, Hy); //G-H
ctx.lineTo(Ix, Iy); //H - I
ctx.arcTo(new RectF(Jx, Jy, Ix, Iy),90,90);// I = J arc
ctx.lineTo(Kx, Ky); //K
ctx.arcTo(new RectF(Ax - arc, Ay, Kx + arc, Ky),180,90); //K - A arc
ctx.lineTo(Ax, Ay); //K
Paint p = new Paint();
p.setAntiAlias(true);
p.setColor(0xffffffff);
p.setStyle(Style.FILL);
canvas.drawPath(ctx, p);
p.setColor(0xff000000);
p.setStyle(Style.STROKE);
p.setStrokeWidth(3);
canvas.drawPath(ctx, p);
}

This answer visually explains all arcTo parameters using four examples.
arcTo takes the following parameters:
public void arcTo(RectF oval,
float startAngle,
float sweepAngle,
boolean forceMoveTo)
where RectF's constructor takes:
RectF(float left, float top, float right, float bottom)
(Hopefully this visualization is less painful and less mystifying than reading the official arcTo documentation.)

Thanks for this example, it makes the parameters very clear to understand.
From what I read in the dev docs of Android you can probably spare yourself some of the "lineTo()" calls (except those to points F,G,H), since arcTo automatically adds a lineTo when the first point of the arc is not the last point drawn...
As for why 0 starts East, it is so because of math and trigonometry lessons generally assume that the 0 degrees mark is the point where the trigonometric circle (circle with center 0,0 and radius 1) intersects with the X-axis, which is East (these same lessons however generally count the angles counter-clockwise, so 90 degrees becomes north and 270 is south, whereas on Android it seems the angles are counted clockwise)

Here's some sample code (pieced together from one of my classes) to draw a filled, rounded corner rectangle and then adding a stroked rectangle to give it a border:
//Initializing some stuff
_paint = new Paint();
_rect = new RectF();
_radius = 10;
_bgColor = 0xFFFFFFFF;
_borderColor = 0xFFCCCCCC;
//Doing dimension calculations
_rect.left = 0;
_rect.top = 0;
_rect.right = this.getWidth() - 1;
_rect.bottom = this.getHeight() - 1;
//painting
//draw the background
_paint.setColor(_bgColor);
_paint.setStyle(Style.FILL_AND_STROKE);
canvas.drawRoundRect(_rect, _radius, _radius, _paint);
//draw the border
_paint.setStrokeWidth(1);
_paint.setColor(_borderColor);
_paint.setStyle(Style.STROKE);
canvas.drawRoundRect(_rect, _radius, _radius, _paint);

Related

Multiple colors for single path Android

Good day.I am creating a siri like wave for android and i encounter an big issue.I need the wave to be in 4 colors.Lets assume i only have one single line which is drawing on the screen accordingly to the voice decibels.Anyway i am able to do it but no way i am able to give 4 different colors for same path.Assume it is 1 single path which moves from screen start to screen end,i need that line to have 4 different colors,mainly i had to divide the path into 4 parts and draw the color for each parts,but neither google,nor any other source give me anything (not even found anything similar to what i want).
Meanwhile i am posting the code where actually i am drawing the lines.
for (int l = 0; l < mWaveCount; ++l) {
float midH = height / 2.0f;
float midW = width / 2.0f;
float maxAmplitude = midH / 2f - 4.0f;
float progress = 1.0f - l * 1.0f / mWaveCount;
float normalAmplitude = (1.5f * progress - 0.5f) * mAmplitude;
float multiplier = (float) Math.min(1.0, (progress / 3.0f * 2.0f) + (1.0f / 3.0f));
if (l != 0) {
mSecondaryPaint.setAlpha((int) (multiplier * 255));
}
mPath.reset();
for (int x = 0; x < width + mDensity; x += mDensity) {
float scaling = 1f - (float) Math.pow(1 / midW * (x - midW), 2);
float y = scaling * maxAmplitude * normalAmplitude * (float) Math.sin(
180 * x * mFrequency / (width * Math.PI) + mPhase) + midH;
// canvas.drawPoint(x, y, l == 0 ? mPrimaryPaint : mSecondaryPaint);
//
// canvas.drawLine(x, y, x, 2*midH - y, mSecondaryPaint);
if (x == 0) {
mPath.moveTo(x, y);
} else {
mPath.lineTo(x, y);
// final float x2 = (x + mLastX) / 2;
// final float y2 = (y + mLastY) / 2;
// mPath.quadTo(x2, y2, x, y);
}
mLastX = x;
mLastY = y;
}
if (l == 0) {
canvas.drawPath(mPath, mPrimaryPaint);
} else {
canvas.drawPath(mPath, mSecondaryPaint);
}
}
I tried to change color on if (l == 0) {
canvas.drawPath(mPath, mPrimaryPaint);
} but if i change it here,no result at all,either the line is separate and not moving at all,but it should,either the color is not applied,propably because i am doing it in loop as i had to and everytime the last color is picked to draw.Anyway can you help me out?Even an small reference is gold for me because really there is nothing at all in the internet.
Anyway even though Matt Horst answer fully correct,i found the simplest and easiest solution...i never thought it would be so easy.Anyway if in world there is someone who need to make an path divided into multiple colors,here is what you can do
int[] rainbow = getRainbowColors();
Shader shader = new LinearGradient(0, 0, 0, width, rainbow,
null, Shader.TileMode.REPEAT);
Matrix matrix = new Matrix();
matrix.setRotate(90);
shader.setLocalMatrix(matrix);
mPrimaryPaint.setShader(shader);
Where getRainbowColors() is an array of colors you wish your line to have and width is the length of the path so the Shader knows how to draw the colors in right way to fit the length of path.Anyway .....easy isnt it?and pretty purged me a lot to get into this simple point.Nowhere in internet you could find only if you are looking for something completelly different,than you might come across this.
It seems to me like you could set up one paint for each section, each with a different color. Then set up one path for each section too. Then as you draw across the screen, wherever the changeover point is between sections, start drawing with the new path. And make sure first to use moveTo() on the new path so it starts off where the old one left off.
For my solution, I tried changing the color of the linePaint in the onDraw Call. But it was drawing a single color.
So i used two different paints for two different colors and draw path on the canvas.
And it worked. Hope it helps someone out there.

How to draw watchface 'ticks' on a square watch?

I currently have this snippet generating the ticks around the outside of and android wear watchface
float innerMainTickRadius = mCenterX - 35;
for(int tickIndex = 0; tickIndex < 12; tickIndex++) {
float tickRot = (float) (tickIndex * Math.PI * 2 / 12);
float innerX = (float) Math.sin(tickRot) * innerMainTickRadius;
float innerY = (float) -Math.cos(tickRot) * innerMainTickRadius;
float outerX = (float) Math.sin(tickRot) * mCenterX;
float outerY = (float) -Math.cos(tickRot) * mCenterX;
canvas.drawLine(mCenterX + innerX, mCenterY + innerY, mCenterX + outerX, mCenterY + outerY, mTickPaint);
}
Which generates the ticks well on a round watchface but on a square it turns out like this:
but I'd like them to not be circular, but instead fit the shape a bit more suitably, e.g:
Is there a standard way to do this? I'm guessing I can't use trig again...
Of course you use geometry and trig. For example any line you put on the clock face you want to point to the center so one part will be the given (x,y) and the other will be arctan2(cy-y,cx-x) giving you the angle from the point you have towards the center (cx,cy) then simply draw the line in the direction of the center of a given length r, by drawing the line from x,y to cos(angle) * r, sin(angle) * r.
However, given your sample image you might want to draw the line from x,y to x+r,y then rotate the canvas by angle so that you can draw those numbers tweaked like that. Be sure to do canvas.save() before tweaking the canvas' matrix and canvas.restore() after the tweak.
This leaves the math of whatever shape you want to draw your ticks from and the positions thereto. You can do this within a Path. So define the path for a rounded rectangle and then use the PathMeasure class to get the getPosTan() and then ignore the tangent and just use the position it gives you to find your position around a rounded rectangle. That or simply calculate those positions as the positions through either a line segment or a bezier section depending on the decided shape.
For example:
static final int TICKS = 12;
static final float TICKLENGTH = 20;
In the draw routine,
float left = cx - 50;
float top = cy - 50;
float right = cx + 50;
float bottom = cy + 50;
float ry = 20;
float rx = 20;
float width = right-left;
float height = bottom-top;
Path path = new Path();
path.moveTo(right, top + ry);
path.rQuadTo(0, -ry, -rx, -ry);
path.rLineTo(-(width - (2 * rx)), 0);
path.rQuadTo(-rx, 0, -rx, ry);
path.rLineTo(0, (height - (2 * ry)));
path.rQuadTo(0, ry, rx, ry);
path.rLineTo((width - (2 * rx)), 0);
path.rQuadTo(rx, 0, rx, -ry);
path.rLineTo(0, -(height - (2 * ry)));
path.close();
PathMeasure pathMeasure = new PathMeasure();
pathMeasure.setPath(path,true);
float length = pathMeasure.getLength();
float[] pos = new float[2];
float r = TICKLENGTH;
for (int i = 0; i < TICKS; i++) {
pathMeasure.getPosTan(i * (length/TICKS),pos,null);
double angle = Math.atan2(cy - pos[1], cx - pos[0]); //yes, y then x.
double cos = Math.cos(angle);
double sin = Math.sin(angle);
canvas.drawLine(pos[0], pos[1], (float)(pos[0] + cos * r), (float)(pos[1] + sin * r), paint);
}
Admittedly it looks like:
So it would take a lot more work to get it looking like your image. But, it's totally doable. The path measure trick thing will work for any shape. I avoided using path.addRoundRect because of the Lollipop+ restriction. You can see my answer to that question here. And the other answers which are plenty fine to how to draw a rounded rectangle-esque shape. You can, if you would like to write an envelope function simply scale your current picture to the envelope of the rectangle according to the factor t, as it goes around the clock.
The angle is a function of the position now. I'm not immediately seeing the trick for getting a closed form in this case. But in the most general case, you could end up just storing the position of each tickmark, then you're just drawing the line that goes through that point and the center. so the angle at second i is just
theta(i)=arctan(y_pos(i) / x_pos(i))
assuming the center has coordinates (0,0). In this case, you only need to store the positions for 8 consecutive ticks because the face is periodic every 90 degrees and symmetric about the diagonals as well.

Best way to draw a path traveled

I'm making a application to track a veicle based in GPS coordinates.
I created a SurfaceView to draw the field, vehicle and the path (route) for him.
The result looked like this:
The black dots represent the coming of GPS coordinates, and blue rectangles would be the area covered by the path traveled. (the width of the path is configurable)
The way I'm drawing with blue rectangles (this is my question) which are the area covered by the path traveled. (the width of the path is configurable)
With that I need to overcome some situation.
I need to calculate the field's rotation angle so that the path always get left behind. (completed)
I need to calculate the angle of rotation of each rectangle so they are facing towards the vehicle. (completed)
In the future I will need:
Detect when the vehicle passes twice in the same place. (based on the path traveled)
Calculate the area (m²) all traveled by the vehicle.
I would like some tips for draw this path.
My code:
public void draw(Canvas canvas) {
Log.d(getClass().getSimpleName(), "draw");
canvas.save();
// translate canvas to vehicle positon
canvas.translate((float) center.cartesian(0), (float) center.cartesian(1));
float fieldRotation = 0;
if (trackerHistory.size() > 1) {
/*
Before drawing the way, only takes the last position and finds the angle of rotation of the field.
*/
Vector lastPosition = new Vector(convertToTerrainCoordinates(lastPoint));
Vector preLastPosition = new Vector(convertToTerrainCoordinates(preLastPoint));
float shift = (float) lastPosition.distanceTo(preLastPosition);
/*
Having the last coordinate as a triangle, 'preLastCoord' saves the values of the legs, while 'shift' is the hypotenuse
*/
// If the Y offset is negative, then the opposite side is the Y displacement
if (preLastPosition.cartesian(1) < 0) {
// dividing the opposite side by hipetenusa, we have the sine of the angle that must be rotated.
double sin = preLastPosition.cartesian(1) / shift;
// when Y is negative, it is necessary to add or subtract 90 degrees depending on the value of X
// The "Math.asin()" calculates the radian arc to the sine previously calculated.
// And the "Math.toDegress()" converts degrees to radians from 0 to 360.
if (preLastPosition.cartesian(0) < 0) {
fieldRotation = (float) (Math.toDegrees(Math.asin(sin)) - 90d);
} else {
fieldRotation = (float) (Math.abs(Math.toDegrees(Math.asin(sin))) + 90d);
}
}
// if not, the opposite side is the X offset
else {
// dividing the opposite side by hipetenusa have the sine of the angle that must be rotated.
double senAngulo = preLastPosition.cartesian(0) / shift;
// The "Math.asin()" calculates the radian arc to the sine previously calculated.
// And the "Math.toDegress()" converts degrees to radians from 0 to 360.
fieldRotation = (float) Math.toDegrees(Math.asin(senAngulo));
}
}
final float dpiTrackerWidth = Navigator.meterToDpi(trackerWidth); // width of rect
final Path positionHistory = new Path(); // to draw the route
final Path circle = new Path(); // to draw the positions
/*
Iterate the historical positions and draw the path
*/
for (int i = 1; i < trackerHistory.size(); i++) {
Vector currentPosition = new Vector(convertToTerrainCoordinates(trackerHistory.get(i))); // vector with X and Y position
Vector lastPosition = new Vector(convertToTerrainCoordinates(trackerHistory.get(i - 1))); // vector with X and Y position
circle.addCircle((float) currentPosition.cartesian(0), (float) currentPosition.cartesian(1), 3, Path.Direction.CW);
circle.addCircle((float) lastPosition.cartesian(0), (float) lastPosition.cartesian(1), 3, Path.Direction.CW);
if (isInsideOfScreen(currentPosition.cartesian(0), currentPosition.cartesian(1)) ||
isInsideOfScreen(lastPosition.cartesian(0), lastPosition.cartesian(1))) {
/*
Calcule degree by triangle sides
*/
float shift = (float) currentPosition.distanceTo(lastPosition);
Vector dif = lastPosition.minus(currentPosition);
float sin = (float) (dif.cartesian(0) / shift);
float degress = (float) Math.toDegrees(Math.asin(sin));
/*
Create a Rect to draw displacement between two coordinates
*/
RectF rect = new RectF();
rect.left = (float) (currentPosition.cartesian(0) - (dpiTrackerWidth / 2));
rect.right = rect.left + dpiTrackerWidth;
rect.top = (float) currentPosition.cartesian(1);
rect.bottom = rect.top - shift;
Path p = new Path();
Matrix m = new Matrix();
p.addRect(rect, Path.Direction.CCW);
m.postRotate(-degress, (float) currentPosition.cartesian(0), (float) currentPosition.cartesian(1));
p.transform(m);
positionHistory.addPath(p);
}
}
// rotates the map to make the route down.
canvas.rotate(fieldRotation);
canvas.drawPath(positionHistory, paint);
canvas.drawPath(circle, paint2);
canvas.restore();
}
My goal is to have something like this application: https://play.google.com/store/apps/details?id=hu.zbertok.machineryguide (but only in 2D for now)
EDIT:
To clarify a bit more my doubts:
I do not have much experience about it. I would like a better way to draw the path. With rectangles it was not very good. Note that the curves are some empty spaces.
Another point is the rotation of rectangles, I'm rotating them at the time of drawing. I believe this will make it difficult to detect overlaps
I believe I need math help for the rotation of objects and overlapping detection. And it also helps to draw the path of a filled shape.
After some research time, I came to a successful outcome. I will comment on my thoughts and how was the solution.
As I explained in question, along the way I have the coordinates traveled by the vehicle, and also a setting for the width of the path should be drawn.
Using LibGDX library is ready a number of features, such as the implementation of a "orthographic camera" to work with positioning, rotation, etc.
With LibGDX I converted GPS coordinates on my side points to the road traveled. Like this:
The next challenge was to fill the path traveled. First I tried using rectangles, but the result was as shown in my question.
So the solution was to trace triangles using the side of the path as vertices. Like this:
Then simply fill in the triangles. Like this:
Finally, using Stencil, I set up OpenGL to highlight overlaps. Like this:
Other issues fixed:
To calculate the covered area, simply calculate the area of existing triangles along the path.
To detect overlapping, just check if the current position of the vehicle is within a triangle.
Thanks to:
AlexWien for the attention and for their time.
Conner Anderson by videos of LibGDX
And a special thanks to Luis Eduardo for knowledge, helped me a lot.
The sample source code.
Usually such a path is drawn using a "path" method from the graphics lib.
In that lib you can create a polyline, and give a line width.
You further specify how corners are filled. (BEVEL_JOIN, MITTER_JOIN)
The main question is wheter the path is drawn while driving or afterwords.
Afterwords is no problem.
To draw while driving might be a bit tricky to avoid to redraw the path each second.
When using the Path with moveTo and lineTo to create a polyline, then you can set a line width, and the graphics lib will do that all for you.
Then there will be no gaps, since it is a poly line.

Drawing an arrow head in android

I am trying to draw an arrow to point to objects in am image. I have been able to write code to draw the line but cant seem to be able to find a way to draw the arrowhead.The code I wrote to draw a dragabble line is as follows.I need to draw an arrowhead on ACTION_UP event to the direction in which the line is pointing
if(event.getAction() ==MotionEvent.ACTION_DOWN) {
if (count==1){
x1 = event.getX();
y1 = event.getY();
System.out.println(count+"count of value a;skd");
Toast.makeText(getApplicationContext(), ""+(radius+count), Toast.LENGTH_LONG).show();
Log.i(TAG, "coordinate x1 : "+String.valueOf(x1)+" y1 : "+String.valueOf(y1));
}
}
else if(event.getAction() ==MotionEvent.ACTION_MOVE){
imageView.setImageBitmap(bmp2);
x2 = event.getX();
y2 = event.getY();
posX=(float)(x1+x2)/2;
posY=(float)(y1+y2)/2;
radius=(float) Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))/2;
onDraw();
Toast.makeText(getApplicationContext(), ""+radius, Toast.LENGTH_LONG).show();
}
Hi, for anyone still needing help .This is how I did it in the end
float h=(float) 30.0;
float phi = (float) Math.atan2(y2 - y1, x2 - x1);
float angle1 = (float) (phi - Math.PI / 6);
float angle2 = (float) (phi + Math.PI / 6);
float x3 = (float) (x2 - h * Math.cos(angle1));
float x4 = (float) (x2 - h * Math.cos(angle2));
float y3 = (float) (y2 - h * Math.sin(angle1));
float y4 = (float) (y2 - h * Math.sin(angle2));
c.drawLine(x1, y1,x2,y2 ,pnt);
c.drawLine(x2, y2,x3,y3 ,pnt);
c.drawLine(x2, y2,x4,y4 ,pnt);
I got help from the accepted answer and ios section in stackoverflow
How I would do this is to find the slope of the line, which is drawn between two points(start and end). The slope would be (dy/dx), and that would be a good start point for your arrow. Assuming you want the base of the arrowhead to be perpendicular to the line of the arrow, to find the slope of the base you would find the opposite reciprocal of the slope of the line. for example, lets say that your line has a slope of 2. The slope for the base of your triangle would be (-1/2), because you do (1/(oldslope)) and multiply by -1. I don't know android very well, but if I remember correctly, in Java, you would use a drawPolygon method, and you would have to specify 4 points(3 unique and 1 the same as the first to close it). Given the slope of the base of the tip, we can get our first two points and our final point. You should know before you start the dimensions of the arrowhead you wish to draw, so in this case b will be the length of your baseline. If you take ϴ=arctan(dy/dx), that will give you an angle between the x axis and your baseline. With that ϴ value, you can do ydif = b*sin(ϴ) to get the difference in y value between the two base corners of your arrow. Doing the same thing but with xdif = b*cos(ϴ) gives you the difference in the x value between the two base points. If the location of the final point of the line that the user drew is, say, (x1, y1), then the locations of the basepoints of the triangle would be (x1-(xdif/2), y1-(ydif/2)) and (x1+(xdif/2), y1+(ydif/2)). These two points, p1 and p2, are the first, second, and fourth points in the draw polygon method. To find the third point, we need to find the angle of the original line, by doing ϴ=arctan(dy/dx), this time using your original dy/dx. with that angle. Before we finish the actual calculation of the point, you first have to know how far from the end of your line the tip of the arrow should actually be, in my case, I will use the var h and h = 10. To get the cordinate, (x,y), assuming the cordinate for the line tip is (x1, y1)you would do (x1+hcosϴ, y1+hsinϴ). Use that for the third value in drawPolygon(), and you should be done. sorry if I kind of rushed at the end, I got kind of tired of typing, comment if you need help.
If you managed to draw a line from the input event, you might additionally draw a triangle on its end indicating the direction.
On another project I drew a square everytime a magnetic point on a grid was touched (as you can see here) Sorry I can not provide you any sample code right now. But if that's a suitable approach for you, I might post it later.
Here is a good code, its not mine, It was a Java Graphics2D code that I converted to Canvas. All credit go to the original guy/lady who wrote it
private void drawArrowHead(Canvas canvas, Point tip, Point tail)
{
double dy = tip.y - tail.y;
double dx = tip.x - tail.x;
double theta = Math.atan2(dy, dx);
int tempX = tip.x ,tempY = tip.y;
//make arrow touch the circle
if(tip.x>tail.x && tip.y==tail.y)
{
tempX = (tip.x-10);
}
else if(tip.x<tail.x && tip.y==tail.y)
{
tempX = (tip.x+10);
}
else if(tip.y>tail.y && tip.x==tail.x)
{
tempY = (tip.y-10);
}
else if(tip.y<tail.y && tip.x==tail.x)
{
tempY = (tip.y+10);
}
else if(tip.x>tail.x || tip.x<tail.x)
{
int rCosTheta = (int) ((10)*Math.cos(theta)) ;
int xx = tip.x - rCosTheta;
int yy = (int) ((xx-tip.x)*(dy/dx) + tip.y);
tempX = xx;
tempY = yy;
}
double x, y, rho = theta + phi;
for(int j = 0; j < 2; j++)
{
x = tempX - arrowLength * Math.cos(rho);
y = tempY - arrowLength * Math.sin(rho);
canvas.drawLine(tempX,tempY,(int)x,(int)y,this.paint);
rho = theta - phi;
}
}
Just call this for both sides of your line and it will draw an arrow at each side!

OpenGL, translate down on y and rotate on z around ELEMENT center (on Android)

I have an orthogonal perspective which I initialize like so:
gl.glViewport(0, 0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0,Constants.GAME_AREA_WIDTH, Constants.GAME_AREA_HEIGHT, 0, 1, 10);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
What I want to do here is have a square start off the top of the screen (at like (x,-100,z) and the that square should descend (on y) while at the same time roate (on z).
The square's upper-left is what I use as reference for the square's position.
Ok, now, I think I get how to roate it around itself. I translate the thing to (-squareSize/2, -squareSize/2,z), rotate it along z, then translate back. And indeed, if I only test this rotation it works ok:
gl.glLoadIdentity();
angle = angle + 3;
if(angle>360) {
angle = angle - 360;
}
gl.glTranslatef(xCurrent+size/2, yCurrent+size/2,0);
gl.glRotatef(angle, 0, 0, 1);
gl.glTranslatef(-(xCurrent+size/2), -(yCurrent+size/2),0);
//omitted: enable client state, draw elements, disable client state.
With just this, no matter where I place my square (even small negative values for x and y which only make it partially show on the screen), it will rotate around its center.
However I can't figure out how to add the downwards translation on y. If I do something like this:
angle = angle + 3;
if(angle>360) {
angle = angle - 360;
}
gl.glTranslatef(xCurrent+size/2, yCurrent+size/2,0);
gl.glRotatef(angle, 0, 0, 1);
gl.glTranslatef(-(xCurrent+size/2), -(yCurrent+size/2),0);
yCurrent = yCurrent + realSpeed;
if(yCurrent>Constants.GAME_AREA_HEIGHT+size) {
yCurrent=-size;
}
gl.glTranslatef(0f, yCurrent,0f);
it will only work ok if my square start at (0,0,z) - in which case it will move down and rotate around it's center.
If however I start it at any positive or negative non 0 value for either x or y, it will still move down, but do a weird spiral motion instead of rotating agains its center.
The OpenGL matrix stack post multiplies. Which effectively means that you should do the most local transformation last.
So what you probably want to do is to perform a glTranslatef to the tile's current position, then do the translate/rotate/untranslate sequence to effect your rotation.
Editor's Note: This answer was moved from a question edit, it is written by the Original Poster.
First off, what Tommy sais in the answer below is right, I should first code the translation to the new position, and THEN add the lines of code that do translate/rotate/translate.
Also, the values I asign to x and y when wanting to translate the center of the square to coordinates (0,0,z) are simply wrong, I misscalculated them. The basic idea here is this. Let's say a square has the following vertices:
private static float xLeft = -0.75f;
private static float xRight = +0.25f;
private static float yTop = 2f;
private static float yBottom = 1f;
protected static float vertices[] = {
//x y z
xLeft, yTop, -5f, //Top left triangle1-1 triangle2-1
xRight, yTop, -5f, //Top right triangle1-2
xLeft, yBottom, -5f, //Bottom left triangle2-3
xRight, yBottom, -5f //Bottom right triangle1-3 triangle2-2
};
then the translation amounts needed to place this square's center at (0,0,z) are:
private float xCenterTranslation = (xRight+xLeft)/2f;
private float yCenterTranslation = (yTop+yBottom)/2f;
and the code for translating the square on the y axis while at the same time rotating it along its center is:
gl.glTranslatef(0, translationAmountLinearY, 0); //translate on y
//decrement Y translation for next rendering
translationAmountLinearY+=translationDeltaLinearY;
gl.glTranslatef(xCenterTranslation, yCenterTranslation, 0);//translate BACK from center
gl.glRotatef(rotationAmountZDegrees, 0, 0, 1);//rotate
gl.glTranslatef(-xCenterTranslation, -yCenterTranslation, 0);//translate to center
//increment z rotation for next rendering:
rotationAmountZDegrees+=0.04f;

Categories

Resources