创建一个圆形ImageButton。舍入正方形图像

时间:2015-07-05 07:54:52

标签: android android-drawable android-imagebutton android-background

我试图在里面创建一个带有图像的ImageButton。 我需要ImageButtons图像有圆边。

但是这里来了但是...而不是让按钮内部的图像更小,以使其适合元素内部,我想让图像角落圆角或切掉。

这是我到目前为止所做的:

drawable:my_image_drawable

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#ffffff" />

    <corners
        android:bottomLeftRadius="50dp"
        android:bottomRightRadius="50dp"
        android:topLeftRadius="50dp"
        android:topRightRadius="50dp" />
</shape>

activity_main.xml中:

<ImageButton
            android:background="@drawable/card_imageview_drawable"
            android:layout_weight="1"
            android:id="@+id/my_image_button"
            android:layout_toRightOf="@+id/my_textview"
            android:src="@drawable/my_image_drawable"
            style="@style/my_imageview_style"/>

这段代码正是我不想做的事情。它使ImageButton中的图像变小,并且不会切割角落

注意:我不能使用ImageView(而不是ImageButton),因为它限制了我可以使用的手势。

欢迎所有建议!谢谢

1 个答案:

答案 0 :(得分:0)

我使用来自另一个StackOverflow线程的代码(我再也找不到了),因为它使用的是java类,我更喜欢以编程方式执行

    public class CustomImageView extends ImageButton {

    public static float radius = 18.0f;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Path clipPath = new Path();
        RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}

然后在XML中调用它:

 <de.termine24.merchant.views.CustomImageView
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:id="@+id/toFillOut"
    android:scaleType="centerCrop"
    android:src="@drawable/empty_contact"/>