创建具有形状的Android ImageButton
我有一个ImageButton,想将按钮缩放到不同的大小,这意味着图像不是正确的选择。所以我想用一个自定义形状作为源的ImageButton 我希望按钮看起来像这样:创建具有形状的Android ImageButton,android,android-layout,Android,Android Layout,我有一个ImageButton,想将按钮缩放到不同的大小,这意味着图像不是正确的选择。所以我想用一个自定义形状作为源的ImageButton 我希望按钮看起来像这样: @Override public void onDraw(Canvas canvas) { width = getMeasuredWidth(); height = getMeasuredHeight(); // diagonal top left | bottom right canvas.dr
@Override
public void onDraw(Canvas canvas)
{
width = getMeasuredWidth();
height = getMeasuredHeight();
// diagonal top left | bottom right
canvas.drawLine(0, 0, width, height, mPaint);
// diagonal top right | bottom left
canvas.drawLine(width, 0, 0, height, mPaint);
// horizontal top
canvas.drawLine(0, 0, width, 0, mPaint);
// horizontal bottom
canvas.drawLine(0, height, width, height, mPaint);
// vertical left
canvas.drawLine(0, 0, 0, height, mPaint);
//vertical right
canvas.drawLine(width, 0, width, height, mPaint);
}
我从这个开始,但被旋转的东西卡住了:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="@color/red" />
<rotate
android:fromDegrees="90"
android:toDegrees="135" >
<shape android:shape="line" >
<stroke
android:width="2dp"
android:color="@color/red" >
</stroke>
</shape>
</rotate>
<padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp" />
</shape>
然而,这并不像我期望的那样旋转。也许我完全错了,需要朝正确的方向努力。:-)谢谢。您是否考虑过使用位图并根据需要使用Bitmap.createScaledBitmap(…)方法对其进行缩放。然后,您可以轻松地将其转换为BitmapDrawable,然后使用(按钮名称)将此BitmapDrawable指定为按钮的背景 因此,你所要做的就是将该图像(帖子中的图像)保存为可绘制图像(可能是透明的PNG),然后将该可绘制图像转换为位图。从这里开始,您只需遵循我上面概述的步骤。希望这有帮助。
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<gradient android:angle="270"
android:endColor="#000000"
android:centerColor="#00ccff"
android:startColor="#000000"
/>
<corners android:radius="5dp" />
</shape>
Try this
试试这个
我用一个自定义的按钮解决了这个问题,并覆盖了onDraw()
方法,如下所示:
@Override
public void onDraw(Canvas canvas)
{
width = getMeasuredWidth();
height = getMeasuredHeight();
// diagonal top left | bottom right
canvas.drawLine(0, 0, width, height, mPaint);
// diagonal top right | bottom left
canvas.drawLine(width, 0, 0, height, mPaint);
// horizontal top
canvas.drawLine(0, 0, width, 0, mPaint);
// horizontal bottom
canvas.drawLine(0, height, width, height, mPaint);
// vertical left
canvas.drawLine(0, 0, 0, height, mPaint);
//vertical right
canvas.drawLine(width, 0, width, height, mPaint);
}
你必须根据颜色和大小等自行设置mPaint
你想要你的笔划。如果我对图像进行高比例缩放,它会被像素化,看起来很糟糕。这可能有效,也可能无效:创建高分辨率,大尺寸的盒子,然后使用我在答案中建议的方法将其重新缩放到更小的尺寸/以满足您的需要。这种方法帮助我防止了像素化,然而,在我的例子中,我不得不将一张大比例的照片缩放到一个小缩略图。让我知道这种方法是否有效。我真的不想这样做。无论如何,谢谢。那是一个完全不同的形状。