1

我有一个从 ImageView 派生的类:

public class TouchView extends ImageView
{
   @Override
   protected void onDraw(Canvas canvas)
   ...

touchview 仅在活动的 onCreate 中创建一次,并使用 SVG 文件中的可绘制对象填充。

ImageView imageView = new TouchView(this);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
FrameLayout f = (FrameLayout)findViewById(R.id.frame2);
FrameLayout.LayoutParams l = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT);
f.addView(imageView, l);
...
is = openFileInput(svgname);
svg = SVGParser.getSVGFromInputStream(is);
is.close();

Drawable d = svg.createPictureDrawable();
imageView.setImageDrawable(d);

所有的环境始终保持不变。然而,在 onDraw 方法中,我在事件之间得到了不同大小的画布。那是代码:

protected void onDraw(Canvas canvas)
{
  super.onDraw(canvas);
  Log.v("DRAW", " w= " + canvas.getWidth() + " h=" + canvas.getHeight());
  ...
}

生成带有线条的日志,其中画布的宽度和高度从正常的 1024*728(这是平板电脑上的正确视图尺寸)到 200*160(在我的图纸中引入错误的奇怪事物)来回变化。我很尴尬。

对于相同的视图/可绘制对象,画布是否应该始终具有相同的大小?文档说 getWidth 和 getHeight 方法返回当前绘图的尺寸,但不清楚是什么层,其中有多少是为“幕后”的画布创建的,以及如何控制这个过程。

我很感激任何关于如何获得一致的绘图行为的解释,特别是通过获取正在绘制的视图的实际大小onDraw

目前,我正在使用调用视图的 getDrawingRect 的工作区,但我不确定这是一种正确的方法,因为似乎 的canvas参数onDraw对于绘图大小应该是完全足够的。

4

1 回答 1

0

我遇到了同样的问题,这是我的解决方法,希望对你有帮助

protected void onDraw(Canvas c) {
    super.onDraw(c);
    int w = getWidth(), h = getHeight();
    // resize
Matrix resize = new Matrix();
resize.postScale((float)Math.min(w, h) / (float)mMarker.getWidth(), (float)Math.min(w, h) / (float)mMarker.getHeight());
imageScaled = Bitmap.createBitmap(mMarker, 0, 0, mMarker.getWidth(), mMarker.getHeight(), resize, false);

c.drawBitmap(imageScaled, 0,0, paint);

}

其中 mMarker 在自定义 ImageView 构造函数中定义。

...
private Bitmap mMarker, imageScaled;
Paint paint = new Paint();


//Java constructor
public AvatarImageView(Context context) {
    super(context);
    init();
}

//XML constructor
public AvatarImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    // load the image only once
    mMarker = BitmapFactory.decodeResource(getResources(), R.drawable.silhouette_48);
    mMarker.setHasAlpha(true);paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(4);

    //invalidate(); // don't know if I need this
}
于 2012-07-24T01:52:37.370 回答