2011-07-18 44 views
0

我需要在android:src和圓角上創建帶有圖像的ImageButton。 我該怎麼做?我還需要爲按鈕設置自定義大小,並且我希望圖像按鈕大小自動調整大小。Android - 帶圓角的ImageButton

+0

爲什麼不使用帶背景圖像的按鈕? – Sujit

+0

@Sujit我該怎麼做?我試試這個: round_button是具有圓角形狀的xml文件。我將背景設置爲此xml,然後我不知道如何將圖像設置爲按鈕。 –

+0

你可以使用android:drawableTop =「@ drawable/icon」將圖片放置在按鈕上方。 – Sujit

回答

2

圓角ImageButton使用它。

@Override 
public void onCreate(Bundle mBundle) { 
super.onCreate(mBundle); 
setContentView(R.layout.main); 

ImageButton image = (ImageButton) findViewById(R.id.img); 
Bitmap bitImg = BitmapFactory.decodeResource(getResources(), 
    R.drawable.default_profile_image); 
image.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
    // TODO Auto-generated method stub 

    Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show(); 
    } 
}); 
image.setImageBitmap(getRoundedCornerImage(bitImg)); 
} 

public static Bitmap getRoundedCornerImage(Bitmap bitmap) { 
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), 
    bitmap.getHeight(), Config.ARGB_8888); 
Canvas canvas = new Canvas(output); 

final int color = 0xff424242; 
final Paint paint = new Paint(); 
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 
final RectF rectF = new RectF(rect); 
final float roundPx = 100; 

paint.setAntiAlias(true); 
canvas.drawARGB(0, 0, 0, 0); 
paint.setColor(color); 
canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 
canvas.drawBitmap(bitmap, rect, rect, paint); 

return output; 

} 

這裏,roundPx是圓形的。 e.g

+0

爲矩形背景設置透明背景或繪製狀態:image_view.setBackgroundColor(Color.parseColor(「#00000000」));並將roundPx設置爲10000以在所有尺寸中循環。 –