[英]How to create a rhombus shaped button in android studio
我想在Material網站上創建一個菱形的按鈕 :
我在網上搜索並沒有找到答案,所以我在這里問。
我已經找到了如何創建菱形形狀:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:height="60dp"
android:width="60dp"
android:right="20dp"
android:left="20dp"
android:gravity="center">
<rotate
android:fromDegrees="45"
android:pivotX="50%"
android:pivotY="50%" >
<shape
android:shape="rectangle">
<solid
android:color="@color/black" />
</shape>
</rotate>
</item>
這是我的圖像按鈕 :
<ImageButton
android:layout_width="85dp"
android:layout_height="85dp"
android:background="@drawable/button_test"
android:src="@drawable/ic_pause_white"
/>
“@ drawable / ic_pause_white”是我導入的暫停圖標矢量。
現在我有一個菱形形狀的暫停按鈕,但我的問題是hitbox與圖像不匹配(如預期的那樣)
我已經嘗試創建一個OnTouchListener
ImageButton btnPlay = findViewById(R.id.btnPlay_Song);
btnPlay.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int eventPadTouch = event.getAction();
float iX=event.getX();
float iY=event.getY();
switch (eventPadTouch) {
case MotionEvent.ACTION_DOWN:
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.button_test);
if (iX>=0 & iY>=0 & iX<bitmap.getWidth() & iY<bitmap.getHeight()) { //Makes sure that X and Y are not less than 0, and no more than the height and width of the image.
if (bitmap.getPixel((int) iX, (int) iY)!=0) {
// actual image area is clicked(alpha not equal to 0), do something
Toast.makeText(ActivityPlayerSong.this, "Play", Toast.LENGTH_SHORT).show();
}
}
return true;
}
return false;
}
});
但我想知道是否有更簡單的方法來做它,如果沒有使用上面的代碼“BitmapFactory.decodeResource(getResources(),R.drawable.button_test)”返回null並且我不知道為什么。
提前感謝所有試圖幫助我的人!
替代更“技術上正確”的解決方案:如果您使用方形背景然后順時針旋轉圖標45度並將整個按鈕逆時針旋轉45度怎么辦?
<ImageButton
android:background="@color/black"
app:srcCompat="@drawable/ic_camera_45deg"
android:rotation="-45"
android:layout_width="48dp"
android:layout_height="48dp"/>
這里的背景是純色,因此您不會得到任何視覺觸摸反饋。 你需要在Android 4上使用<selector>
drawable,在Android 5+上使用<ripple>
drawable。
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="@color/white"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<group
android:pivotX="12"
android:pivotY="12"
android:rotation="45">
<!-- Original paths go here. -->
</group>
</vector>
注意tint
屬性。 如果您的圖標不是24x24,請確保樞軸點位於viewportWidth
和viewportHeight
的中間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.