自定义视图的onDraw接收不同大小的画布

时间:2012-06-02 13:24:06

标签: android android-canvas ondraw

我有一个派生自ImageView的类:

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

touchview仅在活动的onCreate中创建一次,并使用SVG文件中的drawable填充。

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中绘制正在绘制的视图的大小。

目前我正在使用workround调用视图的getDrawingRect,但我不确定它是否正确,因为似乎canvas的{​​{1}}参数应该是全部 - 足以绘制尺寸。

1 个答案:

答案 0 :(得分: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);

}

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

...
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
}