Android how to create triangle and rectangle shape programmatically?

前端 未结 7 943
一整个雨季
一整个雨季 2020-11-29 01:15

How can we create ballon drawable shape as below. where we can change the color of it dynamically. \"enter

相关标签:
7条回答
  • 2020-11-29 02:13

    The clean and right way to do this whilst keeping it dynamic is to extend the View class.

    Then in the onDraw you would do something like this:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    
        drawBackground(canvas);
    }
    
    private void drawBackground(Canvas canvas) {
        int width = (int) mWidth;
        int height = (int) mHeight;
    
        Point a = new Point(0, 0);
        Point b = new Point(width, 0);
        Point c = new Point(width, height - mPointHeight);//mPointedHeight is the length of the triangle... in this case we have it dynamic and can be changed.
        Point d = new Point((width/2)+(mPointedHeight/2), height - mPointHeight);
        Point e = new Point((width/2), height);// this is the sharp point of the triangle
        Point f = new Point((width/2)-(mPointedHeight/2), height - mPointHeight);
        Point g = new Point(0, height - mPointHeight);
    
        Path path = new Path();
        path.moveTo(a.x, a.y);
        path.lineTo(b.x, b.y);
        path.lineTo(c.x, c.y);
        path.lineTo(d.x, d.y);
        path.lineTo(e.x, e.y);
        path.lineTo(f.x, f.y);
        path.lineTo(g.x, g.y);
    
        canvas.drawPath(path, mPointedBackgroundPaint);// mPointedBackgroundPaint is whatever color you want as the fill.
    }
    

    There you go, no unnecessary layering or code that isn't dynamic or clean. You could also add the text in the box too.

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