一.最近工作中有个AI点检项目,需要自定义view继承AppCompatImageView,通过百度识别坐标并传入自定义view中,再同过覆盖onDraw并在绘制边框
主要代码如下:
1.传入百度坐标集合
public void setNewLocation(List<AiResultBean.ResultsBean> list) {
newLocationBeans = list;
}
2.设置图片大小
public void setPicSize(int width, int height) {
this.width = width;
this.height = height;
}
3.重写onDraw方法
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
// 处理标签
if (isShowTag) {
drawTAG(canvas);
}
drawImageDescript(canvas);
}
private void drawTAG(Canvas canvas) {
//canvas.save();
int screenWidth = getScreenWidth();
Paint paint = new Paint();
{
paint.setAntiAlias(true);//用于防止边缘的锯齿
// paint.setColor(Color.BLUE);//设置颜色
paint.setStyle(Paint.Style.STROKE);//设置样式为空心矩形
paint.setStrokeWidth(2.5f);//设置空心矩形边框的宽度
paint.setAlpha(1000);//设置透明度
if (newLocationBeans != null) {
for (AiResultBean.ResultsBean resultsBean : newLocationBeans) {
if (resultsBean.getStatus()==1) {
paint.setColor(Color.GREEN);//设置绿框
} else {
paint.setColor(Color.RED);//设置红框
}
canvas.drawRect(new Rect(resultsBean.getLocation().getLeft() * screenWidth / width, resultsBean.getLocation().getTop() * screenWidth / width, (resultsBean.getLocation().getLeft()
+ resultsBean.getLocation().getWidth()) * screenWidth / width, (resultsBean.getLocation().getTop() + resultsBean.getLocation().getHeight()) * screenWidth / width), paint);//绘制矩形,并设置矩形框显示的位置
}
}
}
}
4.绘制好图片保存至本地
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
tagImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(tagImageView.getDrawingCache());
tagImageView.setDrawingCacheEnabled(false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
String fileName = System.currentTimeMillis() + ".png";
path = fileDir + fileName;
if (!new File(fileDir).exists()) {
new File(fileDir).mkdirs()}
BitmapUtils.writeImage2SD(bitmap, path);
}
}, 500);
}
});
/**
* 把图片写入SD卡
*
* @param bmp
*/
public static void writeImage2SD(Bitmap bmp, String filePath) {
FileOutputStream iStream = null;
File fImage = null;
try {
fImage = new File(filePath);
fImage.createNewFile();
iStream = new FileOutputStream(fImage);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, iStream);
iStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}