Android how to create triangle and rectangle shape programmatically?

前端 未结 7 1071
一整个雨季
一整个雨季 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 01:47

    Create custom view and draw traingle with canvas

    package com.example.dickbutt;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.util.AttributeSet;
    import android.view.View;
    
    public class TriangleShapeView extends View {
    
        public int colorCode = Color.MAGENTA;
    
        public int getColorCode() {
            return colorCode;
        }
    
        public void setColorCode(int colorCode) {
            this.colorCode = colorCode;
        }
    
        public TriangleShapeView(Context context) {
            super(context);
        }
    
        public TriangleShapeView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public TriangleShapeView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            int w = getWidth() / 2;
            int h = getHeight() / 2;
    
            Path path = new Path();
            path.moveTo(0, 0);
            path.lineTo(w, 2 * h);
            path.lineTo(2 * w, 0);
            path.lineTo(0, 0);
    
            path.close();
    
            Paint p = new Paint();
            p.setColor(colorCode);
            p.setAntiAlias(true);
    
            canvas.drawPath(path, p);
        }
    }
    

    Result

    Usage

    
    
    
    

    Advantages

    • Change shape according to width and height of view .
    • Highly customization possible.
    • Look cleaner

提交回复
热议问题