[英]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.