0
我正在創建一個需要不規則形狀按鈕的應用程序。我知道我可以使用圖像按鈕,並將不規則形狀設置爲圖像,但不管圖像的形狀如何,它總是佔據屏幕上的矩形區域。 是否可以讓按鈕佔據圖像的確切形狀? 我是否需要爲此創建自定義控件或佈局,或者是否有其他有效方法? 如果我需要創建一個自定義佈局,那麼我如何確保我放置在佈局上的所有按鈕所包含的空間始終是圓形或橢圓形?應用程序界面上的不規則形狀的按鈕。安卓
我正在創建一個需要不規則形狀按鈕的應用程序。我知道我可以使用圖像按鈕,並將不規則形狀設置爲圖像,但不管圖像的形狀如何,它總是佔據屏幕上的矩形區域。 是否可以讓按鈕佔據圖像的確切形狀? 我是否需要爲此創建自定義控件或佈局,或者是否有其他有效方法? 如果我需要創建一個自定義佈局,那麼我如何確保我放置在佈局上的所有按鈕所包含的空間始終是圓形或橢圓形?應用程序界面上的不規則形狀的按鈕。安卓
你必須重載的onDraw在你需要的形狀的任何觀點方法,看到這個代碼圓的ImageView
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
init(context, null, 0);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
@SuppressLint("DrawAllocation") @Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = null;
int w = getWidth(), h = getHeight();
if (drawable instanceof BitmapDrawable) {
b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
if (drawable instanceof LayerDrawable) {
b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
((LayerDrawable) drawable).setBounds(0, 0, w, h);
((LayerDrawable) drawable).draw(new Canvas(b));
}
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius)
sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
else
sbmp = bmp;
Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(sbmp.getWidth()/2 + 0.7f,
sbmp.getHeight()/2 + 0.7f, sbmp.getWidth()/2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}