[英]How do I inflate a shape to draw on a Canvas?
我在drawables目錄中的xml文件中存儲了一個形狀。 我想在我的Canvas中使用它(我知道我可以在代碼中定義形狀,但是我試圖弄清楚如何以更“ Androidy”的方式實現它)。
我對將形狀顯示在畫布上的語法一無所知。 我應該嘗試將其轉換為Shape還是Drawable? 需要矩陣嗎? 油漆? 等等
我不需要很多細節,只需要指出正確的方向即可:)
謝謝。
[編輯]我的Android XML形狀如下所示:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke android:width="3px" android:color="#583010"/>
<solid android:color="#ffffff" />
<corners android:bottomRightRadius="3px" android:bottomLeftRadius="3px"
android:topLeftRadius="3px" android:topRightRadius="3px"/>
</shape>
我假設一定有某種方法可以使這種膨脹變大,不是嗎? [/編輯]
讓我們將您的文件稱為“ res / drawable / my_shape.xml”。 以下代碼行將從XML填充my_shape.xml並將其內容繪制到Canvas上。 ImageView用於證明這可行。
Drawable shape = getResources().getDrawable(R.drawable.my_shape);
Bitmap bitmap = Bitmap.createBitmap( shape.getIntrinsicWidth(), shape.getIntrinsicHeight(), Config.ARGB_8888 );
Canvas canvas = new Canvas( bitmap );
shape.setBounds( 0, 0, canvas.getWidth(), canvas.getHeight() );
shape.draw( canvas );
ImageView imageView = (ImageView) findViewById(R.id.my_imageView);
imageView.setImageBitmap( bitmap );
確保這些代碼行在onCreate中的setContentView之后執行。
為了消除盡可能多的混亂,這是my_shape.xml的功能示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9"
android:useLevel="false" >
<solid android:color="#DDAAAFFF" />
<size
android:height="10dp"
android:width="10dp" />
<stroke
android:width="1dp"
android:color="#AAAAAA" />
</shape>
定義如何? 像SVG一樣? 您將需要編寫自己的解析器,並將形狀/路徑轉換為對Canvas.drawPath()/Rect()
等的調用。您可以編寫一個自定義視圖,該視圖知道如何繪制自身,等等。為此編寫代碼。 膨脹只是解析XML並創建對象圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.