package com.example.demo_drawcircle; import android.R.color; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Bitmap.Config; import android.view.Menu; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout layout = (LinearLayout) findViewById(R.id.main); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.icon); source = createCircleBitmap(source, 150); ImageView imageView = new ImageView(this); imageView.setImageBitmap(source); layout.addView(imageView,lp); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * * @param source * @param min * @return */ private Bitmap createCircleBitmap(Bitmap source,int min){ Paint paint = new Paint(); paint.setColor(Color.parseColor("#FFFFFF")); paint.setAntiAlias(true);//抗锯齿 Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888); /** * 产生同样大小的画布 */ Canvas canvas = new Canvas(target); /** * 首先绘制圆形 */ canvas.drawCircle(min/2, min/2, min/2, paint); /** * 使用SRC_IN(关键代码) */ paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); /** * 缩放图片 */ //获取这个图片的宽和高 int width = source.getWidth(); int height = source.getHeight(); //计算缩放率,新尺寸除原始尺寸 float scaleWidth = ((float) min) / width; float scaleHeight = ((float) min) / height; // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); //旋转图片 动作 // matrix.postRotate(45); // 创建新的图片 Bitmap newBitmap = Bitmap.createBitmap(source, 0, 0, width, height, matrix, true); /** * 绘制图片 */ canvas.drawBitmap(newBitmap, 0, 0, paint); return target; } }