安卓:调整大小和缩放图像的一部分 [英] Android: Resizing and scaling a part of the image
问题描述
给定一个形象,我希望能够扩展只图像的一部分。再说了,我想扩大一半的图像,这样,有一半占据了整个空间。
Given an image, I want to be able to scale only a part of that image. Say, I want to expand half of the image so that, that half takes up the whole space.
这怎么可能呢?
威尔的ImageView fitXY工作,因为我认为这会为整个原始图像才能正常工作。
Will ImageView fitXY work because I thought it'll work only for the whole original image.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 640;
int newHeight = 480;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// create the new Bitmap object
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 50, 50, width,
height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(bmd);
imageView.setScaleType(ScaleType.CENTER);
linearLayout.addView(imageView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setContentView(linearLayout);
}
}
这仅如果createBitmap,X和源第一像素的Y坐标都是0的意思,我不能把图像的一个子集。仅能够扩展整个图像。但是createBitmap意指到子集的图像。
This works only if in createBitmap, the X and Y coordinates of the first pixels in the source are 0. meaning, I'm not able to take a subset of the image. Only able to scale the whole image. But createBitmap is meant to subset an image.
在日志中,当参数不为0,我得到以下异常:java.lang.IllegalArgumentException异常:X +宽度必须< = bitmap.width()
In the log, when the parameters are not 0, I get the following exception: java.lang.IllegalArgumentException: x + width must be <= bitmap.width()
请帮忙
推荐答案
首先,你必须创建出一种新的位图要使用缩放
First you have to create a new bitmap with the part you want to scale using
createBitmap() //pass the source bitmap, req height and width
现在从结果的位图,必须使用创建缩放位图
Now from the result bitmap, you have to create your scaled bitmap using
createScaledbitmap() //pass the result bitmap , req width, height
有关exapmle:
Bitmap originalBitmap = BitmapFactory.decodeResource(res, id);
Bitmap partImage = originalBitmap.createBitmap(width, height, config);
Bitmap scaledImage = partImage.createScaledBitmap(partImage, dstWidth, dstHeight, filter);
这篇关于安卓:调整大小和缩放图像的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!