3

我想繪製一個帶有洞的矩形。我正試圖通過使用形狀矩形來實現這一點。如何繪製可變筆劃寬度的Android形狀矩形

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <stroke 
     android:width="50dp" 
     android:color="@color/red" /> 
</shape> 

我試圖找出如何我可以改變筆畫寬度,而這個矩形被描繪成是矩形應有例如:在頂部和底部邊緣50 DP筆畫的寬度,但在左側和右側邊緣20 DP 。

我真的很感激你對此的幫助。

+0

我可能會研究層列表,你可能會有更多的運氣。我沒有看到有辦法做到這一點與形狀。 – j2emanue

回答

0

感謝所有您的幫助。我最終重寫了onDraw()以清除佈局的背景顏色,以使用setXfermode()創建矩形孔。

0

我認爲,形狀被用作視圖的背景(例如imageView)。 因此,首先從imageView中獲取Drawable對象,並從中獲取Paint對象。然後你可以修改你想要的任何屬性。

Drawable background = imageView.getBackground(); 
if (background instanceof ShapeDrawable) { 
    // cast to 'ShapeDrawable' 
    ShapeDrawable shapeDrawable = (ShapeDrawable)background; 
    shapeDrawable.getPaint().setStrokeWidth(...); 
} 

相關的問題在這裏:Set android shape color programmatically

+0

感謝您的回覆,但是如何更改矩形左右邊緣的筆觸寬度? – user2124933

+0

我不知道這是否可能。也許你應該實現一個矩形和4行的圖層列表。然後,您可以修改這些線條的筆觸值,使其彼此不同。 – cylon

+0

你能指點我一些例子嗎?這將非常有幫助。 – user2124933

1

下面是如何你可以用一個層列表做一個例子:我會改變的左上角和右上角的屬性是這樣的:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item> 
     <shape android:shape="rectangle"> 
      <solid android:color="@android:color/transparent"/> 
     </shape> 
    </item> 

    <item android:top="1dp"> 
     <shape android:shape="rectangle"> 
      <solid android:color="@android:color/holo_blue_bright"/> 
     </shape> 
    </item> 

    <item android:left="3dp"> 
     <shape android:shape="rectangle"> 
      <gradient android:angle="270" android:startColor="#8C2300" android:endColor="#D34617"/> 
     </shape> 
    </item> 

    <item android:right="8dp"> 
     <shape android:shape="rectangle"> 
      <gradient android:angle="270" android:startColor="#000000" android:endColor="#ffc0cb"/> 
     </shape> 
    </item> 

</layer-list> 

在您的可繪製文件夾中調用此文件與layers.xml類似。然後應用它作爲背景,以您的看法是這樣的:

android:background="@drawable/shape"