效果如下
我是使用的资源图片
music.png
icon_arround1.png
代码如下
public class MainActivity extends AppCompatActivity {
int sIconOutpreWidth = 200; // 外层图像的宽度
int sIconInpreWidth = 100; // 内层图像的宽度
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.music);
Bitmap compositeBitmap =GetTaoBitmap(this,originalBitmap);
ImageView iv = findViewById(R.id.iv_music);
iv.setImageBitmap(compositeBitmap);
}
Bitmap GetTaoBitmap(Context context, Bitmap bp){
// 获取原始位图,获取了一个Bitmap对象
Bitmap wfrBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_arround1);
// 创建一个新的空白位图,宽度和高度均为 sIconOutpreWidth,使用ARGB_8888配置
Bitmap target = Bitmap.createBitmap(sIconOutpreWidth, sIconOutpreWidth, Bitmap.Config.ARGB_8888);
// 创建一个画布并绑定到目标位图上
Canvas canvas = new Canvas(target);
// 获取传入位图bp的宽度和高度
int width = bp.getWidth();
int height = bp.getHeight();
Log.d("MainActivity","width:"+width); // 270
Log.d("MainActivity","height:"+height);// 270
// 计算缩放比例,使得传入位图的宽度和高度分别缩放到sIconInpreWidth
float scaleWidth = ((float) sIconInpreWidth) / width; // 100 / 270 = 0.37
float scaleHeight = ((float) sIconInpreWidth) / height;// 100 / 270 = 0.37
// 创建一个Matrix对象,用于执行缩放变换
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 使用Matrix对象创建一个新的缩放后的位图resizedBitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bp, 0, 0, width, height, matrix, true);
// 将缩放后的位图resizedBitmap绘制到目标位图target上,使其居中对齐
canvas.drawBitmap(resizedBitmap, (sIconOutpreWidth - sIconInpreWidth) / 2, (sIconOutpreWidth - sIconInpreWidth) / 2, null);
// 将资源位图wfrBitmap绘制到目标位图target上,绘制区域是从(0, 0)到(sIconOutpreWidth, sIconOutpreWidth)
canvas.drawBitmap(
wfrBitmap, // 需要绘制的bitmap
// 指定要从源位图中裁剪的矩形区域。Rect 的构造函数接受四个整数参数,表示矩形的左、上、右、下边界的坐标。
new Rect(0, 0, wfrBitmap.getWidth(), wfrBitmap.getHeight()),
// 在目标画布上绘制的区域
new RectF(0, 0, sIconOutpreWidth, sIconOutpreWidth),// 在画布中指定绘制bitmap的区域,当这个区域的面积与bitmap要显示的面积不匹配时,会进行拉伸
null
);
// 保存当前画布的状态
canvas.save();
// 恢复画布的状态,确保绘制操作完成
canvas.restore();
// 返回最终合成的目标位图
return target;
}
}