如何旋转抗锯齿可拉伸启用抗锯齿

2023-09-04 13:26:38 作者:转身ン伴寂寞

我需要几度来旋转ImageView的。我通过继承的ImageView和重载这样的OnDraw()

I need to rotate an ImageView by a few degrees. I'm doing this by subclassing ImageView and overloading onDraw()

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.scale(0.92f,0.92f);
    canvas.translate(14, 0);
    canvas.rotate(1,0,0);
    super.onDraw(canvas);
    canvas.restore();
}

现在的问题是,这一结果的图象显示一串锯齿的。

The problem is that the image that results shows a bunch of jaggies.

我怎样才能消除锯齿,我需要以消除锯齿来旋转ImageView的?有没有更好的方式来做到这一点?

How can I antialias an ImageView that I need to rotate in order to eliminate jaggies? Is there a better way to do this?

推荐答案

如果你知道你的绘制对象是一个BitmapDrawable,你可以使用抗锯齿位图的绘制做类似如下:

If you know that your Drawable is a BitmapDrawable, you can use anti-aliasing in the bitmap's Paint to do something like the following:

/**
 * Not as full featured as ImageView.onDraw().  Does not handle 
 * drawables other than BitmapDrawable, crop to padding, or other adjustments.
 */
@Override
protected void onDraw(Canvas canvas) {
    final Drawable d = getDrawable();

    if( d!=null && d instanceof BitmapDrawable && ((BitmapDrawable)d).getBitmap()!=null ) {
        final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        final int paddingLeft = getPaddingLeft();
        final int paddingTop = getPaddingTop();

        canvas.save();

        // do my rotation and other adjustments
        canvas.scale(0.92f,0.92f);
        canvas.rotate(1,0,0);

        if( paddingLeft!=0 )
            canvas.translate(paddingLeft,0);

        if( paddingTop!=0 )
            canvas.translate(0,paddingTop);

        canvas.drawBitmap( ((BitmapDrawable)d).getBitmap(),0,0,p );
        canvas.restore();
    }
}