2014-09-10 288 views
10

我該如何創建一個如下圖所示的梯形形狀?如何在android中構建一個梯形形狀?

enter image description here

我不想用圖片或9.png。

+1

使用std用自定義形狀 – pskink 2014-09-10 14:49:50

+0

使用矢量繪製ShapeDrawable:見我的回答如下。 – 2017-03-21 13:50:47

+0

檢查這個[答案](http://stackoverflow.com/questions/41551094/how-to-create-leaning-list-items/41622884#41622884) – 2017-03-23 12:28:58

回答

12

試試這個:

<?xml version="1.0" encoding="utf-8"?> 
<vector xmlns:android="http://schemas.android.com/apk/res/android" 
    android:width="292dp" 
    android:height="172dp" 
    android:viewportWidth="292" 
    android:viewportHeight="172"> 

    <path 
     android:strokeWidth="1.5" 
     android:strokeMiterLimit="10" 
     android:pathData="M 27.046 96.615 L 16.416 150.396 L 271.534 150.396 L 186.495 22.836 L 37.676 22.836 L 27.046 86.615 Z" /> 

    <path 
     android:fillColor="#00ff00" 
     android:strokeWidth="1.5" 
     android:strokeMiterLimit="10" 
     android:pathData="M 16.046 20.615 L 13.416 150.396 L 271.534 150.396 L 186.495 22.836 L 37.676 22.836 L 16.046 23.615 Z " /> 
</vector> 

enter image description here

+0

我推薦這個答案。看到我的答案[這裏](http://stackoverflow.com/a/42145439/7292819)鏈接到文檔和一個例子,這將給如何使用這個更多的想法。 – Gary99 2017-03-28 01:22:52

+0

對不起我的問題,但你爲什麼第一次使用 ??? – 2017-03-28 04:26:27

2

這個類是一個View定義,並繪製一個梯形ShapeDrawable。因此,梯形,作爲Drawable,也可用於背景。

package com.stackoverflow.questions.q25768037; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Path; 
import android.graphics.drawable.ShapeDrawable; 
import android.graphics.drawable.shapes.PathShape; 
import android.util.AttributeSet; 
import android.view.View; 

public class TrapezoidView extends View { 

    private ShapeDrawable mTrapezoid; 

    public TrapezoidView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     Path path = new Path(); 
     path.moveTo(0.0f, 0.0f); 
     path.lineTo(100.0f, 0.0f); 
     path.lineTo(200.0f, 100.0f); 
     path.lineTo(0.0f, 100.0f); 
     path.lineTo(0.0f, 0.0f); 

     mTrapezoid = new ShapeDrawable(new PathShape(path, 200.0f, 100.0f)); 
     mTrapezoid.getPaint().setStyle(Paint.Style.FILL_AND_STROKE); 
     mTrapezoid.getPaint().setStrokeWidth(1.0f); 
     mTrapezoid.getPaint().setColor(Color.GREEN); 
    } 

    @Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     mTrapezoid.setBounds(0, 0, w, h); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     mTrapezoid.draw(canvas); 
    } 
}