2013/12/15

Android で 円をきりとる。

タイトル微妙。
なんて表現していいかわからないがこんな感じの円を切り取ってつくる

よくある方法はカスタム View 作って ごにょごにょするんだろうけど XML でもこういうのは簡単にできる。

まずは円形のshapeをつくる

<?xml version="1.0" encoding="utf-8"?>
<!-- 円形の shape を作る -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#8000FF00" />
<stroke
android:width="5dp" />
</shape>


ソレを元に clip リソース作成

<?xml version="1.0" encoding="utf-8"?>
<!-- 作った shape を元に clip を作る -->
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="vertical"
android:drawable="@drawable/shape_oval_text_background"
android:gravity="bottom|clip_vertical" />


clip を TextView の背景にする

<!-- TextView の背景に clip を指定 -->
<TextView
android:id="@+id/text_view"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@drawable/clip_text_background"
android:gravity="bottom|center_horizontal"
android:paddingBottom="30dp"
android:text="@string/hello_world"
android:textColor="#FF0000"
android:textSize="22sp" />
view raw gistfile1.xml hosted with ❤ by GitHub


ClipDrawable をもってきてレベルを指定

// ClipDrawable を持ってきてレベルを指定
TextView textView = (TextView) this.findViewById(R.id.text_view);
ClipDrawable background = (ClipDrawable) textView.getBackground();
background.setLevel(background.getLevel() + 2500);
view raw gistfile2.java hosted with ❤ by GitHub


ね?簡単でしょ?

ちなみに、clipリソースの gravity を center にするとこんなふうになる。
いろいろ変えると表現の幅が広がりますね。

マニュアルはここ