重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
本篇文章給大家分享的是有關如何給Android應用設置圓角圖片,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
主要原理是使用系統自帶api:
RoundedBitmapDrawableFactory
public class MainActivity extends AppCompatActivity { private ImageView mImgRectRound; private ImageView mImgRound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImgRectRound = (ImageView) findViewById(R.id.img_rect_rounded); mImgRound = (ImageView) findViewById(R.id.img_rounded); rectRoundBitmap(); roundBitmap(); } private void rectRoundBitmap(){ //得到資源文件的BitMap Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.dog); //創建RoundedBitmapDrawable對象 RoundedBitmapDrawable roundImg =RoundedBitmapDrawableFactory.create(getResources(),image); //抗鋸齒 roundImg.setAntiAlias(true); //設置圓角半徑 roundImg.setCornerRadius(30); //設置顯示圖片 mImgRectRound.setImageDrawable(roundImg); } private void roundBitmap(){ //如果是圓的時候,我們應該把bitmap圖片進行剪切成正方形, 然后再設置圓角半徑為正方形邊長的一半即可 Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.dog); Bitmap bitmap = null; //將長方形圖片裁剪成正方形圖片 if (image.getWidth() == image.getHeight()) { bitmap = Bitmap.createBitmap(image, image.getWidth() / 2 - image.getHeight() / 2, 0, image.getHeight(), image.getHeight()); } else { bitmap = Bitmap.createBitmap(image, 0, image.getHeight() / 2 - image.getWidth() / 2, image.getWidth(), image.getWidth()); } RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap); //圓角半徑為正方形邊長的一半 roundedBitmapDrawable.setCornerRadius(bitmap.getWidth() / 2); //抗鋸齒 roundedBitmapDrawable.setAntiAlias(true); mImgRound.setImageDrawable(roundedBitmapDrawable); } }