Android解決ImageView setRotation....等旋轉時出現鋸齒問題

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

/**
 * Created by DengDongQi on 2019/9/3
 * 解決ImageView  setRotationX....等旋轉時出現鋸齒問題
 *
 * 原理 : 某大佬研究出鋸齒規律會出現爲ImageView的邊界 1-2 px處,解決辦法是:
 * 重寫onDraw且不走super方法,自己縮小ImageView內容1-2 px並居中繪製
 *
 * 出處: (FQ)https://medium.com/@elye.project/smoothen-jagged-edges-of-rotated-image-view-1e56f6d8b5e9
 */
public class RotationImageView extends ImageView {

    public RotationImageView(Context context) {
        super(context);
    }

    public RotationImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RotationImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() instanceof BitmapDrawable) {
            //super.onDraw(canvas); 不走super
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setDither(true);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            BitmapShader shader = new BitmapShader(bitmap,
                    Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

            Matrix matrix = new Matrix();
            float scale;
            /* Note: this piece of code handling like Centre-Crop scaling */
            if (bitmap.getWidth() > bitmap.getHeight()) {
                scale = (float) canvas.getHeight() / (float) bitmap.getHeight();
                matrix.setScale(scale, scale);
                matrix.postTranslate((canvas.getWidth() - bitmap.getWidth() * scale) * 0.5f, 0);

            } else {
                scale = (float) canvas.getWidth() / (float) bitmap.getWidth();
                matrix.setScale(scale, scale);
                matrix.postTranslate(0, (canvas.getHeight() - bitmap.getHeight() * scale) * 0.5f);
            }
            shader.setLocalMatrix(matrix);

            paint.setShader(shader);
            /* this is where I shrink the image by 1px each side,
                move it to the center */
            canvas.translate(2, 2);
            canvas.drawRect(
                    0.0f, 0.0f, canvas.getWidth() - 4, canvas.getHeight() - 4, paint);

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章