Custom path line style when drawing on canvas

前端 未结 2 1761
不思量自难忘°
不思量自难忘° 2021-02-02 03:01

I\'m currently working on map overlay which highlights the route along specified points and I need to implement certain line style (something like on screenshot)

2条回答
  •  爱一瞬间的悲伤
    2021-02-02 03:21

    I managed to find a better solution for my problem. So I got rid of my custom path effect and started to use usual stroke. So I basically draw my path 2 times: at first I draw black line, after that I draw thiner transparent line to clear the center of previous black line.

    The only trick in this approach is that I need to draw my path in a separate bitmap (using temp canvas) and when path bitmap is ready - render it to the main canvas.

    Hope this will help somebody else

    @Override
    public void draw(Canvas canvas, final MapView mapView, boolean shadow)
    {
        //Generate new bitmap if old bitmap doesn't equal to the screen size (f.i. when screen orientation changes)
        if(pathBitmap == null || pathBitmap.isRecycled() || pathBitmap.getWidth()!=canvas.getWidth() || pathBitmap.getHeight()!=canvas.getHeight())
        {
            if(pathBitmap != null)
            {        
                pathBitmap.recycle();
            }
            pathBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.ARGB_8888);
            tempCanvas.setBitmap(pathBitmap);
        }
    
        //Render routes to the temporary bitmap
        renderPathBitmap();
    
        //Render temporary bitmap onto main canvas
        canvas.drawBitmap(pathBitmap, 0, 0, null);
        }
    }
    
    private void renderPath(Path path, Canvas canvas)
    {
        routePaint.setStrokeWidth(ROUTE_LINE_WIDTH);
        routePaint.setColor(OUTER_COLOR);
        routePaint.setXfermode(null);
    
        canvas.drawPath(path, routePaint); //render outer line
    
        routePaint.setStrokeWidth(ROUTE_LINE_WIDTH/1.7f);
        routePaint.setColor(Color.TRANSPARENT);
        routePaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
    
        canvas.drawPath(path, routePaint); //render inner line
    }
    

    So result looks like:

    enter image description here

提交回复
热议问题