【问题标题】:Creating a round ImageButton. Rounding a square image创建一个圆形 ImageButton。将方形图像四舍五入
【发布时间】:2015-07-05 18:33:48
【问题描述】:

我正在尝试创建一个带有图像的 ImageButton。 我需要 ImageButtons 图像具有圆形边缘。

但是问题来了……我不想让按钮内的图像更小,以使其适合元素内部,我想让图像的角变圆或切掉。

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

可绘制: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),因为它限制了我可以使用的手势。

欢迎所有建议!谢谢

【问题讨论】:

  • 你用过scaleType="fitCentre"
  • 在上面的链接中,找到提到 Romain Guy(著名的 Android 软件工程师)的答案
  • 嗨。感谢您的回答。所以没有 XML 解决方案,但我必须以编程方式创建圆边?这很奇怪......

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


【解决方案1】:

我使用来自另一个 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"/>

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2018-12-31
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多