
在开发过程中有时需要将图片显示成圆角图片,一般我们可以通过在xml中设置drawable shape即可,但今天我给出另一种方法,用java代码动态去设置圆角,顺便做个简单的笔记。
主要原理是使用系统自带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,image.getHeight(),image.getHeight()); } else { bitmap = Bitmap.createBitmap(image,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); }}布局文件:
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:ID="@+ID/activity_main" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" tools:context="com.cjl.roundedbitmap.MainActivity"> <ImageVIEw androID:ID="@+ID/img_rect_rounded" androID:layout_wIDth="200dp" androID:layout_height="300dp" androID:layout_margintop="20dp" androID:layout_gravity="center_horizontal"/> <ImageVIEw androID:ID="@+ID/img_rounded" androID:layout_margintop="20dp" androID:layout_wIDth="200dp" androID:layout_height="200dp" androID:layout_gravity="center_horizontal"/></linearLayout>
如有问题,欢迎指正,谢谢。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android如何设置圆角图片全部内容,希望文章能够帮你解决Android如何设置圆角图片所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)