package com.example.testandroid;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;
public class MyProgress extends View
{
private float scale;
private float dx;
private float dy;
private int mBorderWidth;
public MyProgress(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.hello);
//圆形图片实现方式001
bitmap = getRoundedCornerBitmap(bitmap, 1);
Rect rect2 = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect rect3 = new Rect(200, 200, 400, 400);
Paint paint4 = new Paint();
paint4.setAntiAlias(true);
canvas.drawBitmap(bitmap, rect2, rect3, paint4);
//圆形图片实现方式002
//中点cx,cy,半径radius
canvas.drawCircle(500, 300, 200, getPaint(bitmap));
}
private Paint getPaint(Bitmap bitmap)
{
int outWidth = 200;
int outHeight = 200;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Paint paint = new Paint();
paint.setAntiAlias(true);
Shader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
Matrix localM = new Matrix();
if (width * outHeight > outWidth * height)
{
scale = outHeight / (float) height;
dx = (outWidth - width * scale) * 0.5f;
} else
{
scale = outWidth / (float) width;
dy = (outHeight - height * scale) * 0.5f;
}
//localM.setScale(scale, scale);
//localM.postTranslate((int) (dx + 0.5f) + mBorderWidth,
// (int) (dy + 0.5f) + mBorderWidth);
System.out.println("缩放比例:"+scale);
shader.setLocalMatrix(localM);
paint.setShader(shader);
return paint;
}
/**
* 将图片截取为圆角图片
*
* @param bitmap
* 原图片
* @param ratio
* 截取比例,如果是8,则圆角半径是宽高的1/8,如果是2,则是圆形图片
* @return 圆角矩形图片
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float ratio)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(width,
height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, width, height);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
// 不能少.........
canvas.drawRoundRect(rectF, width / ratio,
height / ratio, paint);
// 圆形,少了就不是圆形.............
// 圆形,少了就不是圆形.............
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}