我需要将ImageView旋转几度。我是通过继承ImageView并重载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();
}
问题是结果的图像显示出一堆锯齿状。
http://img.skitch.com/20100608-gmdy4sexsm1c71di9rgiktdjhu.png
我如何消除我需要旋转的ImageView才能消除锯齿?有更好的方法吗?
答案 0 :(得分:5)
如果您知道您的Drawable是BitmapDrawable,您可以在位图的Paint中使用消除锯齿来执行以下操作:
/**
* 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();
}
}
答案 1 :(得分:4)
将antialias和filterBitmap设置为绘制位图的绘画。 我有类似的问题,这对我有用:
Paint bitmapPaint = new Paint();
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
答案 2 :(得分:1)
我做了以下工作让它发挥作用:
在AndroidManifest.xml
我启用了硬件加速<application android:hardwareAccelerated="true">
。
我没有使用自定义绘图方法,而是将父视图的图层类型更改为硬件加速并启用了抗锯齿,并添加了我的子视图,如下所示:
Paint layerPaint = new Paint();
layerPaint.setAntiAlias(true);
layerPaint.setFilterBitmap(true);
layerPaint.setDither(true);
RelativeLayout parentLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.myLayout, null);
parentLayout.setLayerType(View.LAYER_TYPE_HARDWARE, layerPaint);
parentLayout.addView(myChildView);
我必须补充一点,使用这种方法时无法禁用裁剪。
答案 3 :(得分:0)
这种旋转只能解决问题的一部分 - 锯齿状边缘,但图像反而变得奇怪。
ifound只有一个解决方案: 在提取或派遣抽签方法
Bitmap bmp = ((BitmapDrawable)image.getDrawable()).getBitmap();
double scale = (0.0+bmp.getWidth()+40.0)/getWidth();
if (scale > 1){
bmp = Bitmap.createScaledBitmap(bmp, getWidth()-40, (int) (bmp.getHeight()/scale), true);
}
canvas.drawColor(Color.TRANSPARENT);
canvas.save();
canvas.translate(20, yShift);
int left = borderSize;
int top = borderSize;
int right = bmp.getWidth() - borderSize;
int bottom = bmp.getHeight() - borderSize;
if(showText){
mPaint.setColor(Color.WHITE);
canvas.rotate(getAngel());
canvas.drawRect(left, top, right, bottom, mPaint);
canvas.translate(0,0);
textFrame.draw(canvas);
}else{
// rotaed bitmap
mMatrix.setRotate(getAngel());
// draw bitmap after creation of new rotated bitmap from rotated matrix
canvas.drawBitmap(Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mMatrix, true)
, 0, 0, mPaint);
}
canvas.restore();
答案 4 :(得分:0)
@Primoz990的解决方案对我有用:)我也启用了抖动,所以我的最终代码可以消除旋转时的锯齿状边缘:
Paint bitmapPaint = new Paint();
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
bitmapPaint.setDither(true);