目标: 把一张正方形的图片裁剪成为圆形的图片
1.第一步布局好.xml文件
在RelativeLayout 相对布局中放置两个一样大的图片控件: imageView2覆盖在imageView1上面
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:gravity="center"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#000000" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@mipmap/test" />
</RelativeLayout>
2.第二步,在代码中对控件做裁剪,关键代码:
//setOval(left, top, right, bottom);
outline.setOval(0 , 0 , view.getWidth(), view.getHeight());
view,setOval(int left, int top, int right, int bottom);
参数含义; 圆形的 左,上,右,下 4个顶点
坐标以需要裁剪的view控件为参考坐标:
public class MainActivity extends AppCompatActivity {
private Context context;
private ImageView iv;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView2);
context = this;
iv.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0 , 0 , view.getWidth(), view.getHeight());
// outline.setOval(0 - i, 0 - i, view.getHeight() + i, view.getHeight() + i);
}
});
iv.setClipToOutline(true);
}
}
3.运行结果:裁剪的图片正好与原来的图片内相切