【发布时间】:2013-11-21 18:20:50
【问题描述】:
我正在开发一款 Android 游戏,但我有一个问题一直在尝试解决。
我有一个自定义视图,我已经覆盖了它的onDraw 和onMeasure。此自定义视图位于 LinearLayout 或 RelativeLayout 内,如下所示
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_weight="2">
<com.leftcorner.craftersofwar.images.BitmapView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
现在的问题是,在onMeasure 函数中,父级的大小为 0。我唯一能做的就是根据所需的内容大小缩放我的视图。但是,如果位图大于视图的最终尺寸,当我输入onDraw 函数时,这将导致画布错位。画布的 (0, 0) 坐标位于视图本身的边缘上方。
我可以在使用((View) this.getParent()).getWidth(); 绘制之前获取父尺寸,将位图尺寸与之比较并以正确的比例绘制位图,但将其绘制到画布上失败,因为位图超出了视图边界我不知道位置。
那么,我怎样才能将我的这个位图绘制到画布上以便它真正可见?如果它也在视图中居中会更好。
这是我目前拥有的代码:
@Override
protected void onDraw(Canvas canvas) {
pWidth = ((View) this.getParent()).getWidth();
pHeight = ((View) this.getParent()).getHeight();
fWidth = Utility.smaller(pWidth, bWidth);
fHeight = Utility.smaller(pHeight, bHeight);
if(bitmap != null){
// As you can see, I'm not using a custom bitmap class.
// This function draws the bitmap to the canvas.
// (x, y, width, height, canvas)
bitmap.getStorageBitmap().drawScaledBitmap(0, 0, fWidth, fHeight, canvas);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
bWidth = Math.round(bitmap.getWidth() * scale);
bHeight = Math.round(bitmap.getHeight() * scale);
if(bitmap != null) setMeasuredDimension(bWidth, bHeight);
else setMeasuredDimension(0, 0);
}
【问题讨论】:
标签: android view bitmap android-canvas