我有一个在 HorizontalScrollView 中定义了 ImageView 的 Activity 。图像源是一个 9 补丁文件,该文件被限制为仅拉伸(stretch)右边缘以填满屏幕。我实现了一个简单的缩放功能,允许用户通过调整位图大小并将新位图分配给 View 来双击放大和缩小。我当前的问题是,当我双击重新缩小时,当我将新调整大小的位图分配给 View 时,不会应用 9 补丁。换句话说,它不是像 9 补丁文件中定义的那样只拉伸(stretch)右边缘,而是拉伸(stretch)整个图像。
这是我的 XML:
<HorizontalScrollView
android:id="@+id/hScroll"
android:fillViewport="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="none" >
<RelativeLayout
android:id="@+id/rlayoutScrollMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/imgResultMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="@drawable/map_base"/>
</RelativeLayout>
</horizontalScrollView>
这是我的代码的相关部分,在 onDoubleTap() 调用中:
public boolean onDoubleTap(MotionEvent e)
{
if (zoom == 1) {
zoom = 2; // zoom out
} else {
zoom = 1; // zoom in
}
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.map_base);
Bitmap bmp = Bitmap.createScaledBitmap(image, image.getWidth() * zoom, image.getHeight() * zoom, false);
ImageView imgResultMap = (ImageView)findViewById(R.id.imgResultMap);
imgResultMap.setImageBitmap(bmp);
return false;
}
编辑:经过一些研究,我弄明白了。除了操纵位图之外,我还需要包括 9 补丁 block ,它不是位图图像的一部分,以重新构建一个新的 9 补丁可绘制对象。请参阅下面的示例代码:
...
else {
// Zoom out
zoom = 1;
Bitmap mapBitmapScaled = mapBitmap;
// Load the 9-patch data chunk and apply to the view
byte[] chunk = mapBitmap.getNinePatchChunk();
NinePatchDrawable mapNinePatch = new NinePatchDrawable(getResources(),
mapBitmapScaled, chunk, new Rect(), null);
imgResultMap.setImageDrawable(mapNinePatch);
}
....
最佳答案
编辑:经过一些研究,我弄明白了。除了操纵位图之外,我还需要包括 9 补丁 block ,它不是位图图像的一部分,以重新构建一个新的 9 补丁可绘制对象。请参阅下面的示例代码:
...
else {
// Zoom out
zoom = 1;
Bitmap mapBitmapScaled = mapBitmap;
// Load the 9-patch data chunk and apply to the view
byte[] chunk = mapBitmap.getNinePatchChunk();
NinePatchDrawable mapNinePatch = new NinePatchDrawable(getResources(),
mapBitmapScaled, chunk, new Rect(), null);
imgResultMap.setImageDrawable(mapNinePatch);
}
....
编辑 #2:对于那些在此处查看我的解决方案的人,还可以查看 Kai 下面关于内存管理的建议。非常有用的信息。
关于android - 如何以编程方式将 9 补丁图像重新应用到 ImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10623570/