Android Bitmap 图片裁剪

时间:2024-01-27 13:52:19
private void clipBitmap() {
    // 创建原始位图对象
    Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_cast_background);
    // 创建新的空白画布对象
    int width = ScreenUtil.dp2px(this,550);
    int height = ScreenUtil.dp2px(this,452);
    // 创建新的画布大小为550X452位图对象
    Bitmap croppedImage = Bitmap.createBitmap(width, height, originalImage.getConfig());
    // 创建画布并将其与新的位图关联起来
    Canvas canvas = new Canvas(croppedImage);
    canvas.drawARGB(0, 0, 0, 0); // 设置画布透明度为完全不透明(默认值)
    // 定义要剪切的区域
    int left = ScreenUtil.dp2px(this,120);
    int top = ScreenUtil.dp2px(this,116);
    int right = ScreenUtil.dp2px(this,120 + width);
    int bottom = ScreenUtil.dp2px(this,116 + height);
    // 左上角到右下角的矩形区域
    Rect srcRect = new Rect(left, top, right, bottom);
    // 目标矩形区域
    Rect destRect = new Rect(0, 0, width, height);
    // 调用 drawBitmap() 函数进行剪切操作
    canvas.drawBitmap(originalImage, srcRect, destRect, null);
    // 显示或保存剪切后的图片
    ImageView imageView = findViewById(R.id.cast_bg);
    imageView.setImageBitmap(croppedImage);
}