在自定义ImageView后面绘制一个矩形而不是动画

时间:2015-10-14 10:01:55

标签: android imageview android-canvas custom-view

我需要一个自定义的图像视图,它首先在图像后面绘制一些形状,然后使用应用于实际位图本身的相同“缩放”来绘制图像。一切都很好,除了我有一个AlphaAnimation淡入自定义ImageView。它淡化BitmapDrawable部分,但不是我的形状。 Shape始终以完全不透明度绘制。我已经尝试将我正在使用的油漆的alpha设置为视图的getAlpha,但没有运气。这是我的自定义ImageView类中的onDraw函数:

@Override
protected void onDraw(Canvas canvas) {
    float[] f = new float[9];
    getImageMatrix().getValues(f);

    final float scaleX = f[Matrix.MSCALE_X];
    final float scaleY = f[Matrix.MSCALE_Y];

    final Drawable d = getDrawable();
    final int origW = d.getIntrinsicWidth();
    final int origH = d.getIntrinsicHeight();

    final int actW = Math.round(origW * scaleX);
    final int actH = Math.round(origH * scaleY);

    canvas.drawRect(Math.max((getWidth() - actW) / 2, 0) + 1, Math.max((getHeight() - actH) / 2, 0) + 1, Math.max((getWidth() - actW) / 2, 0) + actW - 1, Math.max((getHeight() - actH) / 2, 0) + actH - 1, paint);
    super.onDraw(canvas);
}

2 个答案:

答案 0 :(得分:1)

快速解决您的问题的方法是将自定义视图添加到某种视图容器中,然后只是为容器设置动画。

答案 1 :(得分:0)

这是imageView的onDraw方法的source code版本:5.0.0_r1

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mDrawable == null) {
        return; // couldn't resolve the URI
    }

    if (mDrawableWidth == 0 || mDrawableHeight == 0) {
        return;     // nothing to draw (empty bounds)
    }

    if (mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0) {
        mDrawable.draw(canvas);
    } else {
        int saveCount = canvas.getSaveCount();
        canvas.save();

        if (mCropToPadding) {
            final int scrollX = mScrollX;
            final int scrollY = mScrollY;
            canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
                    scrollX + mRight - mLeft - mPaddingRight,
                    scrollY + mBottom - mTop - mPaddingBottom);
        }

        canvas.translate(mPaddingLeft, mPaddingTop);

        if (mDrawMatrix != null) {
            canvas.concat(mDrawMatrix);
        }
        mDrawable.draw(canvas);
        canvas.restoreToCount(saveCount);
    }
}

如你所见,这里没有使用Paint,所以我敢打赌这是你的问题。尝试创建新的Paint并将其alpha设置为Drawable.getAlpha()

由于Drawable.getAlpha()需要API 19,你可以将它包装在你自己的Drawable中,如下所示:

class MyDrawable extends Drawable {

    final Drawable originalDrawable;
    private int mAlpha = 1;

    @Override
    public int getAlpha() {
        return mAlpha;
    }

    public MyDrawable(Drawable drawable){
        originalDrawable = drawable;
    }

    @Override
    public void draw(Canvas canvas) {
        originalDrawable.draw(canvas);
    }

    @Override
    public void setAlpha(int alpha) {
        mAlpha = alpha;
        originalDrawable.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        originalDrawable.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return originalDrawable.getOpacity();
    }
}