How to achieve filling a path object on a canvas? - android

I have a problem filling a path drawn on a canvas.
I read all those previous questions saying
Paint red = new Paint();
red.setColor(Color.RED);
red.setStyle(Paint.Style.FILL_AND_STROKE);
should be the way it works. Then I drew my Path like
Path p = new Path();
p.moveTo(100,100); //point1
p.lineTo(200,200);
p.moveTo(200,200); //point2
p.lineTo(100,200);
p.moveTo(100,200); //point3
p.lineTo(100,100);
p.close();
Which should be a closed path in my opinion.
After canvas.drawPath(p, red);
the triangle/path is drawn but not filled although style is FILL_AND_STROKE.
What am I getting wrong?

There is no path to fill because your path consists of multiple lines, but no coherent polygon. See moveTo documentation, which reads:
Set the beginning of the next contour to the point (x,y).
So by calling moveTo you are only drawing lines.
Only use lineTo(), which also "moves" to the target position. And you can skip the last lineTo() going to the point of origin, close() will do this automatically.
// create a triangle
Path p = new Path();
p.moveTo(100,100); //p1
p.lineTo(200,200); //p2
p.lineTo(100,200); //p3
p.close();

Related

Android - how to properly draw an arrow with Path?

I'm trying to draw an arrow but I get a really strange result.
This is how it looks like and the problem is pretty clear - the overlapping part.
int radius = 100; //Radius of blue circle to the right
Path leftArrow = new Path();
Paint leftArrowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
leftArrowPaint.setStyle(Paint.Style.STROKE);
leftArrowPaint.setColor(ContextCompat.getColor(getContext(), R.color.buttonText));
leftArrowPaint.setAlpha(80);
leftArrowPaint.setStrokeWidth(8);
Within onDraw method:
//Start point
leftArrow.moveTo(touchX-(radius+5), (int)touchY);
//Line to left
leftArrow.lineTo(touchX-(radius+60), (int)touchY);
//Line up
leftArrow.lineTo(touchX-(radius+30), (int)touchY-30);
//Move back to the middle
leftArrow.moveTo(touchX-(radius+60), (int)touchY);
//Line down
leftArrow.lineTo(touchX-(radius+30), (int)touchY+30);
canvas.drawPath(leftArrow, leftArrowPaint);
leftArrow.reset();
Ok, I know it's too late for you, but I'm gonna answer anyway in case someone comes across the same problem.
You need to specify the Paint's Join property.
https://developer.android.com/reference/android/graphics/Paint.Join.html
leftArrowPaint.setStrokeJoin(Paint.Join.BEVEL);
You can also use Paint.Join.ROUND, depending on what looks better for you.

i have got two android draw but i dont know why one work and second not

This code work and draw a ok:
paintComponent(canvas);
p=new Paint();
p.setColor(Color.RED);
for(int i=1;i<pointA.size();i++){
int beginx=pointA.get(i-1).x, beginy=pointA.get(i-1).y,endx= pointA.get(i).x,endy= pointA.get(i).y;
canvas.drawLine(beginx,beginy ,endx,endy, p);
Log.e("matej",beginx+"endy"+beginy+"endx"+endx+"endy"+endy);
}
//canvas.drawLine(0, 181, xtest, ytest, p);
//canvas.drawPath(path, p);
This code drawing not good all draw from one point but i dont know why:
paintComponent(canvas);
p=new Paint();
p.setColor(Color.RED);
Path path1=new Path();
path1.moveTo(pointA.get(0).x, pointA.get(0).y);
for(int i=1;i<pointA.size();i=i+2){
int beginx=pointA.get(i-1).x, beginy=pointA.get(i-1).y,endx= pointA.get(i).x,endy= pointA.get(i).y;
path1.moveTo(pointA.get(i-1).x,pointA.get(i-1).y);
path1.lineTo(pointA.get(i).x, pointA.get(i).y);
Log.e("matej","beginx "+beginx+"beginy "+beginy+"endx "+endx+"endy "+endy);
And finly i want to know what i fail in second code and i want know which code is faster :) tnx
You declare lots of int values (beginx, beginy, etc) and don't actually use them, I'd suggest using them or deleting them for clarity.
You're also skipping out some points, IE
i = 1:
moveTo(0, 0)
lineTo(1, 1)
i = 3:
moveTo(2, 2)
lineTo(3, 3)
So no line is drawn between (1,1) and (2,2)
You also never call canvas.drawPath() so I'm not entirely sure how anything is getting drawn to the screen in the second example.

Canvas Drawing Accuracy Problems

Someone help me understand the crazy Canvas class in Android. It doesn't seem accurate and I am not quite sure why the parameters are floating point values. For example, here is the polygon I want to draw, with absolute point values:
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(false);
mPaint.setDither(false);
mPaint.setFilterBitmap(false);
Path path1 = new Path();
path1.moveTo(151, 100);
path1.lineTo(200, 200);
path1.lineTo(100, 151);
path1.lineTo(200, 151);
path1.lineTo(100, 201);
path1.lineTo(151, 100);
// So that these points constitute a closed polygon
path1.setFillType(Path.FillType.EVEN_ODD);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.GRAY);
// Draw the polygon
mCanvas.drawPath(path1, mPaint);
When I run similar code in Windows with the Windows GDI, it nails the points exactly. In android, however, there are two problems:
1) The line seems anti-aliased (there are blackish-pixels around the gray lines) even though I turned off anti-aliasing.
2) It doesn't always hit the specified points. Sometimes it does, sometimes it doesn't
In order to get closer to the points I wanted, I have to do this:
Path path1 = new Path();
path1.moveTo(151, 100-1);
path1.lineTo(200+1, 200+1);
path1.lineTo(100-1, 151);
path1.lineTo(200+2, 151);
path1.lineTo(100, 201);
path1.lineTo(151+1, 100);
I can't figure out the rules here or what its doing that is so odd.
That is nore like the Path class what you mean and not the Canvas. Now I recommend you to set the dither to true mPaint.setDither(true), allow me to quote the dither method:
Helper for setFlags(), setting or clearing the DITHER_FLAG bit Dithering affects how colors that are higher precision than the device are down-sampled. No dithering is generally faster, but higher precision colors are just truncated down (e.g. 8888 -> 565). Dithering tries to distribute the error inherent in this process, to reduce the visual artifacts.
in other words it tells you that there could be an issue parsing the colors.
So that could be the one that is causing you the issue.

trouble in making a game questions?

all i've a little trouble understanding some concepts while making game please give your suggestions on my questions.
I have a animated sprite image this i want to move this image according to given path. I can get path from
Path path = new Path();
Point s = new Point(150, 5);
Point cp1 = new Point(140, 125);
Point cp2 = new Point(145, 150);
Point e = new Point(200, 250);
path.moveTo(s.x, s.y);
path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);
canvas.drawPath(path, paint);
these points are hard coded and give different results on different screen.
Q1. How can i make path which is similar in all screen size?
Q2. How can i move my animated sprite image according to given path with the image has it's head according to path?

How can I tell if a closed path contains a given point?

In Android, I have a Path object which I happen to know defines a closed path, and I need to figure out if a given point is contained within the path. What I was hoping for was something along the lines of
path.contains(int x, int y)
but that doesn't seem to exist.
The specific reason I'm looking for this is because I have a collection of shapes on screen defined as paths, and I want to figure out which one the user clicked on. If there is a better way to be approaching this such as using different UI elements rather than doing it "the hard way" myself, I'm open to suggestions.
I'm open to writing an algorithm myself if I have to, but that means different research I guess.
Here is what I did and it seems to work:
RectF rectF = new RectF();
path.computeBounds(rectF, true);
region = new Region();
region.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));
Now you can use the region.contains(x,y) method.
Point point = new Point();
mapView.getProjection().toPixels(geoPoint, point);
if (region.contains(point.x, point.y)) {
// Within the path.
}
** Update on 6/7/2010 **
The region.setPath method will cause my app to crash (no warning message) if the rectF is too large. Here is my solution:
// Get the screen rect. If this intersects with the path's rect
// then lets display this zone. The rectF will become the
// intersection of the two rects. This will decrease the size therefor no more crashes.
Rect drawableRect = new Rect();
mapView.getDrawingRect(drawableRect);
if (rectF.intersects(drawableRect.left, drawableRect.top, drawableRect.right, drawableRect.bottom)) {
// ... Display Zone.
}
The android.graphics.Path class doesn't have such a method. The Canvas class does have a clipping region that can be set to a path, there is no way to test it against a point. You might try Canvas.quickReject, testing against a single point rectangle (or a 1x1 Rect). I don't know if that would really check against the path or just the enclosing rectangle, though.
The Region class clearly only keeps track of the containing rectangle.
You might consider drawing each of your regions into an 8-bit alpha layer Bitmap with each Path filled in it's own 'color' value (make sure anti-aliasing is turned off in your Paint). This creates kind of a mask for each path filled with an index to the path that filled it. Then you could just use the pixel value as an index into your list of paths.
Bitmap lookup = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
//do this so that regions outside any path have a default
//path index of 255
lookup.eraseColor(0xFF000000);
Canvas canvas = new Canvas(lookup);
Paint paint = new Paint();
//these are defaults, you only need them if reusing a Paint
paint.setAntiAlias(false);
paint.setStyle(Paint.Style.FILL);
for(int i=0;i<paths.size();i++)
{
paint.setColor(i<<24); // use only alpha value for color 0xXX000000
canvas.drawPath(paths.get(i), paint);
}
Then look up points,
int pathIndex = lookup.getPixel(x, y);
pathIndex >>>= 24;
Be sure to check for 255 (no path) if there are unfilled points.
WebKit's SkiaUtils has a C++ work-around for Randy Findley's bug:
bool SkPathContainsPoint(SkPath* originalPath, const FloatPoint& point, SkPath::FillType ft)
{
SkRegion rgn;
SkRegion clip;
SkPath::FillType originalFillType = originalPath->getFillType();
const SkPath* path = originalPath;
SkPath scaledPath;
int scale = 1;
SkRect bounds = originalPath->getBounds();
// We can immediately return false if the point is outside the bounding rect
if (!bounds.contains(SkFloatToScalar(point.x()), SkFloatToScalar(point.y())))
return false;
originalPath->setFillType(ft);
// Skia has trouble with coordinates close to the max signed 16-bit values
// If we have those, we need to scale.
//
// TODO: remove this code once Skia is patched to work properly with large
// values
const SkScalar kMaxCoordinate = SkIntToScalar(1<<15);
SkScalar biggestCoord = std::max(std::max(std::max(bounds.fRight, bounds.fBottom), -bounds.fLeft), -bounds.fTop);
if (biggestCoord > kMaxCoordinate) {
scale = SkScalarCeil(SkScalarDiv(biggestCoord, kMaxCoordinate));
SkMatrix m;
m.setScale(SkScalarInvert(SkIntToScalar(scale)), SkScalarInvert(SkIntToScalar(scale)));
originalPath->transform(m, &scaledPath);
path = &scaledPath;
}
int x = static_cast<int>(floorf(point.x() / scale));
int y = static_cast<int>(floorf(point.y() / scale));
clip.setRect(x, y, x + 1, y + 1);
bool contains = rgn.setPath(*path, clip);
originalPath->setFillType(originalFillType);
return contains;
}
I know I'm a bit late to the party, but I would solve this problem by thinking about it like determining whether or not a point is in a polygon.
http://en.wikipedia.org/wiki/Point_in_polygon
The math computes more slowly when you're looking at Bezier splines instead of line segments, but drawing a ray from the point still works.
For completeness, I want to make a couple notes here:
As of API 19, there is an intersection operation for Paths. You could create a very small square path around your test point, intersect it with the Path, and see if the result is empty or not.
You can convert Paths to Regions and do a contains() operation. However Regions work in integer coordinates, and I think they use transformed (pixel) coordinates, so you'll have to work with that. I also suspect that the conversion process is computationally intensive.
The edge-crossing algorithm that Hans posted is good and quick, but you have to be very careful for certain corner cases such as when the ray passes directly through a vertex, or intersects a horizontal edge, or when round-off error is a problem, which it always is.
The winding number method is pretty much fool proof, but involves a lot of trig and is computationally expensive.
This paper by Dan Sunday gives a hybrid algorithm that's as accurate as the winding number but as computationally simple as the ray-casting algorithm. It blew me away how elegant it was.
See https://stackoverflow.com/a/33974251/338479 for my code which will do point-in-path calculation for a path consisting of line segments, arcs, and circles.

Categories

Resources