2011-07-18 43 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以在所有尺寸中循环。 –