2013-03-06 104 views
26

我試圖用OvalShape繪製自定義ShapeDrawable,並用白色和灰色邊框填充。我創建像這樣的繪製:在Android上繪製具有邊框(圓角半徑)的以編程方式呈橢圓形狀

ShapeDrawable drawable = new ShapeDrawable(new OvalShape()); 
drawable.getPaint().setColor(Color.GRAY); 
drawable.getPaint().setStyle(Style.STROKE); 
drawable.getPaint().setStrokeWidth(getPixels(5)); 
drawable.getPaint().setAntiAlias(true); 

但後來的結果:corners problem

enter image description here

的想法是通過編程來創建一個形狀像這樣的,但不同的顏色:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="oval"> 
<corners android:radius="10dip"/> 
<stroke android:color="#FF0000" android:width="5dip"/> 
<solid android:color="@android:color/transparent"/> 
</shape> 

如何解決這個問題?

+0

你是說,問題是鏈接圖像中顯示的邊框的剪裁? – 2013-03-06 12:55:57

+0

是的!如果筆畫寬度爲0(髮際線),但沒有解決方案對我來說沒有問題。順便說一句getPixels()方法會返回像素,但我認爲這不是問題。 – L3K0V 2013-03-06 13:07:19

+0

我認爲問題在於你的drawable的大小。您需要減小尺寸以適應邊框的寬度。 – 2013-03-06 13:35:46

回答

1

這是一個新的解決方案:

RoundedBitmapDrawable RBD = RoundedBitmapDrawableFactory.create(mContext.getResources(),YourBitmap); 
      RBD.setCornerRadius(20); 
      RBD.setAntiAlias(true); 

      wholeRel.setBackground(RBD); 
42

我找到了一種解決新建drawable的方法!

一個定義的邊界從圓的Android XML如下:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="oval"> 
<corners android:radius="10dip"/> 
<stroke android:color="#FF0000" android:width="5dip"/> 
<solid android:color="@android:color/transparent"/> 
</shape> 

然後,當想改變顏色繪製的,我申請ColorFilter。例如,如果我想繪製的紅色變爲藍色我這樣做:

Drawable drawable = context.getResources().getDrawable(R.drawable.name); 
drawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP); 

如果我們要使用StateListDrawable從代碼創建自定義的選擇要注意 - StateListDrawable可以清除應用於繪圖資源過濾器...上應用過濾器整個選擇器由selector.setColorFilter...修復問題。

+0

即可添加填充我遇到了一個問題:無法執行'LinearLayout.addView(drawable,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f));' – 2013-10-22 06:55:48

+0

您試圖將drawable添加到佈局而不是view ...創建圖像視圖或圖像按鈕,然後設置在將其添加到佈局並關閉課程之前將其添加到佈局中。 – L3K0V 2013-10-23 09:11:29

+0

你知道我怎樣才能以編程方式更改背景顏色? – 2013-12-18 13:43:38