本篇文章给大家分享的是有关如何给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);
}
}
布局文件:
<?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应用设置圆角图片,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。