How to draw filled polygon?

前端 未结 8 2101
生来不讨喜
生来不讨喜 2020-12-01 08:57

How to draw filled polygon in Android ?

相关标签:
8条回答
  • 2020-12-01 09:37

    BTW - I discovered that once you begin creating your path, any moveTo commands within the path will mean that the shape is left unfilled.

    It makes sense when you think about it, that Android/Java would leave the shape unfilled as the moveTo would represent a break in the polygon.

    However I've seen some tutorials like this How to draw a filled triangle in android canvas?

    which have moveTo's after each lineTo. Even though this may result in an unbroken polygon, Android assumes that a moveTo represents a break in the polygon.

    0 讨论(0)
  • 2020-12-01 09:40

    Android does not have a handy drawPolygon(x_array, y_array, numberofpoints) action like Java. You have to walk through making a Path object point by point. For example, to make a filled trapezoid shape for a 3D dungeon wall, you could put all your points in x and y arrays then code as follows:

    Paint wallpaint = new Paint();
    wallpaint.setColor(Color.GRAY);
    wallpaint.setStyle(Style.FILL);
    
    Path wallpath = new Path();
    wallpath.reset(); // only needed when reusing this path for a new build
    wallpath.moveTo(x[0], y[0]); // used for first point
    wallpath.lineTo(x[1], y[1]);
    wallpath.lineTo(x[2], y[2]);
    wallpath.lineTo(x[3], y[3]);
    wallpath.lineTo(x[0], y[0]); // there is a setLastPoint action but i found it not to work as expected
    
    canvas.drawPath(wallpath, wallpaint);
    

    To add a constant linear gradient for some depth, you could code as follows. Note y[0] is used twice to keep the gradient horizontal:

     wallPaint.reset(); // precaution when resusing Paint object, here shader replaces solid GRAY anyway
     wallPaint.setShader(new LinearGradient(x[0], y[0], x[1], y[0], Color.GRAY, Color.DKGRAY,TileMode.CLAMP)); 
    
     canvas.drawPath(wallpath, wallpaint);
    

    Refer to Paint, Path and Canvas documentation for more options, such as array defined gradients, adding arcs, and laying a Bitmap over your polygon.

    0 讨论(0)
提交回复
热议问题