我正在尝试在画布上绘制矩形,它在android设备MotoC Plus 7.0上运行良好,但在某些设备上却无法正常工作,例如Xiaome Redmi 8.0。在调试代码后,我发现invalidate不会通过在Xiaome Redmi 8.0中调用onDraw方法来更新视图,但是对于Motoc Plus 7.0,正在调用onDraw方法。以下是我的自定义视图,任何人都可以注意到我在这里犯了什么错误:
public class CustomImageView extends View {
private Paint mRectPaint;
private int mStartX = 0;
private int mStartY = 0;
private int mEndX = 0;
private int mEndY = 0;
private boolean mDrawRect = false;
private Bitmap mBitmap;
private double scale;
public void invalidate(boolean mDrawRect) {
this.mDrawRect = mDrawRect;
}
public CustomImageView(final Context context) {
super(context);
init();
}
public CustomImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomImageView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setContent(Bitmap bitmap, List<Point> pointList, boolean mDrawRect) {
this.mBitmap = bitmap;
this.mDrawRect = mDrawRect;
if (pointList != null && pointList.get(0) != null && pointList.get(1) != null)
setValue(pointList);
//setWillNotDraw(false);
invalidate();
}
private void setValue(List<Point> pointList) {
mStartX = (int) ((int) Math.min(pointList.get(0).x, pointList.get(1).x) * scale);
mStartY = (int) ((int) Math.min(pointList.get(0).y, pointList.get(1).y) * scale);
mEndX = (int) ((int) Math.max(pointList.get(1).x, pointList.get(0).x) * scale);
mEndY = (int) ((int) Math.max(pointList.get(1).y, pointList.get(0).y) * scale);
Log.e("mStartX,mStartY :: ", mStartX +","+mStartY);
Log.e("mEndX,mEndY :: ", mEndX +","+mEndY);
}
private void init() {
mRectPaint = new Paint();
mRectPaint.setColor(Color.parseColor("#55000000"));
mRectPaint.setStyle(Paint.Style.FILL);
mRectPaint.setStrokeWidth(5);
mRectPaint.setStrokeJoin(Paint.Join.ROUND);
mRectPaint.setAntiAlias(true);
mRectPaint.setDither(true);
//setWillNotDraw(false);
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
this.scale = drawBitmap(canvas);
if (mDrawRect) {
canvas.drawRect(Math.min(mStartX, mEndX), Math.min(mStartY, mEndY),
Math.max(mEndX, mStartX), Math.max(mEndY, mStartY),
mRectPaint);
}
}
private double drawBitmap(Canvas canvas) {
double viewWidth = canvas.getWidth();
double viewHeight = canvas.getHeight();
double imageWidth = mBitmap.getWidth();
double imageHeight = mBitmap.getHeight();
double scale = Math.min(viewWidth / imageWidth, viewHeight / imageHeight);
Rect destBounds = new Rect(0, 0, (int) (imageWidth * scale), (int) (imageHeight * scale));
canvas.drawBitmap(mBitmap, null, destBounds, null);
return scale;
}
public double getScale() {
return scale;
}
}
答案 0 :(得分:0)
通过更改方法名称解决了问题
public void invalidate(boolean mDrawRect) {
this.mDrawRect = mDrawRect;
}
到
public void invalidateCustomview(boolean mDrawRect) {
this.mDrawRect = mDrawRect;
}