Ale*_*aux 9 android antialiasing rounded-corners imageview
我是android dev的新手,现在我已经尝试了几个小时为ImageView添加漂亮而光滑的圆角,但没有成功.
我尝试的第一件事就是直接对我的图像进行圆角处理,但这意味着要更改位图,因为我需要保留原始位图,而且这些都非常大,这对内存不友好.这也会导致其他困难,因为我的ImageView是流动的.
我尝试使用的第二件事是继承我的视图后的clipPath方法.这有效,但角落是别名.然后我尝试添加一个PaintFlagsDrawFilter来实现别名,但这没有用.我正在使用monodroid,我想知道这应该用于Java.
这是我的代码(C#):
public class MyImageView : ImageView
{
private float[] roundedCorner;
/**
* Contains the rounded corners for the view.
* You can define one, four or height values.
* This behaves as the css border-radius property
*
* @see http://developer.android.com/reference/android/graphics/Path.html#addRoundRect(android.graphics.RectF, float[], android.graphics.Path.Direction)
*/
public float[] RoundedCorners{
get{
return roundedCorner;
}
set{
float[] finalValue = new float[8];
int i=0;
if(value.Length == 1){
for(i=0; i<8;i++){
finalValue[i] = value[0];
}
}else if(value.Length == 4){
for(i=0; i<4;i++){
finalValue[2*i] = value[i];
finalValue[2*i+1] = value[i];
}
}
roundedCorner = finalValue;
}
}
public SquareImageView (Context context) :
base (context)
{
Initialize ();
}
public SquareImageView (Context context, IAttributeSet attrs) :
base (context, attrs)
{
Initialize ();
}
private void Initialize ()
{
RoundedCorners = new float[]{0,0,0,0};
}
public override void Draw (Android.Graphics.Canvas canvas)
{
Path path = new Path();
path.AddRoundRect(new RectF(0,0, Width,Height),RoundedCorners, Path.Direction.Cw);
canvas.ClipPath(path);
base.Draw (canvas);
}
/**
* try to add antialiasing.
*/
protected override void DispatchDraw (Canvas canvas)
{
canvas.DrawFilter = new PaintFlagsDrawFilter((PaintFlags)1, PaintFlags.AntiAlias);
base.DispatchDraw (canvas);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
使用下面的代码
public Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
{
Bitmap output = null;
if(bitmap != null)
{
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
}
return output;
}
Run Code Online (Sandbox Code Playgroud)
并像这样调用这个方法
imageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 10));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5257 次 |
| 最近记录: |