Android实现圆角图片
程序员文章站
2022-06-27 19:00:09
本文实例为大家分享了android实现圆角图片的具体代码,供大家参考,具体内容如下效果图:快速开始activity_main.xml文件:
本文实例为大家分享了android实现圆角图片的具体代码,供大家参考,具体内容如下
效果图:
快速开始
activity_main.xml文件:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <imageview android:id="@+id/iv_img" android:layout_width="300dp" android:layout_height="200dp" android:layout_margintop="30dp" android:src="@mipmap/image_bg" app:layout_constraintright_torightof="parent" app:layout_constraintleft_toleftof="parent" app:layout_constrainttop_totopof="parent"/> <imageview android:id="@+id/iv_rect_img" android:layout_width="300dp" android:layout_height="200dp" android:layout_margintop="30dp" app:layout_constraintright_torightof="parent" app:layout_constraintleft_toleftof="parent" app:layout_constrainttop_tobottomof="@id/iv_img"/> <imageview android:id="@+id/iv_circle_img" android:layout_width="200dp" android:layout_height="200dp" android:layout_margintop="30dp" app:layout_constraintleft_toleftof="parent" app:layout_constraintright_torightof="parent" app:layout_constrainttop_tobottomof="@id/iv_rect_img"/> </android.support.constraint.constraintlayout>
mainactivity.class文件:
public class mainactivity extends appcompatactivity { private imageview ivrectimg, ivcircleimg; private bitmap bitmap; private int width; private int height; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); ivrectimg = findviewbyid(r.id.iv_rect_img); ivcircleimg = findviewbyid(r.id.iv_circle_img); bitmap = bitmapfactory.decoderesource(getresources(), r.mipmap.image_bg); width = bitmap.getwidth(); height = bitmap.getheight(); rectroundbitmap(); circlebitmap(); } // 圆角矩形 private void rectroundbitmap() { roundedbitmapdrawable bitmapdrawable = roundedbitmapdrawablefactory.create(getresources(), bitmap); bitmapdrawable.setantialias(true); bitmapdrawable.setcornerradius(50); ivrectimg.setimagedrawable(bitmapdrawable); } // 把bitmap图片进行剪切成正方形, 然后再设置圆角半径为正方形边长的一半即可 private void circlebitmap() { bitmap circle = null; int min = math.min(width, height); int max = math.max(width, height); if (width == height) { circle = bitmap.createbitmap(bitmap, 0, 0, width, height); } else { // 居中裁剪 if (width > height) { circle = bitmap.createbitmap(bitmap, (max - min) / 2, 0, min, min); } else { circle = bitmap.createbitmap(bitmap, 0, (max - min) / 2, min, min); } } roundedbitmapdrawable bitmapdrawable = roundedbitmapdrawablefactory.create(getresources(), circle); bitmapdrawable.setcornerradius(min / 2); bitmapdrawable.setantialias(true); ivcircleimg.setimagedrawable(bitmapdrawable); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。