我正在尝试使用缩放功能创建一个自定义视图,但它在我的下面的代码中没有显示任何内容。因为这里请求的是我当前如何缩放位图,请注意我正在寻找另一种缩放方法整个画布。这是我的onDraw()方法的细节,但是完整的方法在项目放置方面有更多的逻辑,在缩放之前我检查一个布尔标志,如果用户选择了缩放但我想你不想筛选那么多代码,所以我只是把相关的东西放在这里。
private final int bgColor = 8355711;
private Paint paint;
private Bitmap bgBitmap;
private float scaleFactor = 1;
private final float minScaleFactor = 0.25f, maxScaleFactor = 10f;
private ScaleGestureDetector scaleDetector;
public OratorView(Context context) {
super(context, null, 0);
// init(context);
}
public OratorView(Context context, AttributeSet set) {
super(context, set, 0);
init(context);
}
public OratorView(Context context, AttributeSet set, int defStyle) {
super(context, set, defStyle);
init(context);
}
private void init(Context context) {
if (null == scaleDetector)
this.scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
this.paint = new Paint();
this.paint.setColor(bgColor);
}
public void setBackground(Bitmap bitmap) {
this.bgBitmap = bitmap;
bgScaled = false;
}
private boolean bgScaled = false;
private void scaleBg() {
if (null != bgBitmap) {
if (bgBitmap.getWidth() > 0 && bgBitmap.getHeight() > 0) {
float widthFactor = (float) bgBitmap.getWidth() / (float) getWidth();
float heightFactor = (float) bgBitmap.getHeight() / (float) getHeight();
float scale = widthFactor > heightFactor ? widthFactor : heightFactor;
bgBitmap = Bitmap.createScaledBitmap(bgBitmap, (int) (bgBitmap.getWidth() / scale), (int) (bgBitmap.getHeight() / scale),
true);
bgScaled = true;
}
invalidate();
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
c.save();
c.scale(scaleFactor, scaleFactor);
// fill background with solid color
c.drawColor(bgColor);
if (!bgScaled) {
scaleBg();
}
// draw background image if any
if (null != bgBitmap) {
c.drawBitmap(bgBitmap, (getWidth() - bgBitmap.getWidth()) / 2, (getHeight() - bgBitmap.getHeight()) / 2, paint);
}
c.restore();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
scaleDetector.onTouchEvent(ev);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
Log.d("OratorView", "onScale - scaleFactor=" + scaleFactor);
if (scaleFactor >= maxScaleFactor && scaleFactor <= maxScaleFactor) {
scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f));
invalidate();
}
return true;
}
}
答案 0 :(得分:0)
我认为问题出在您的ScaleListener.onScale方法中。这是我正在讨论的代码块:
if (scaleFactor >= maxScaleFactor && scaleFactor <= maxScaleFactor) {
scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f));
invalidate();
}
只有scaleFactor == maxScaleFactor才会出现这种情况。由于如果此条件为真,您只是使视图无效,只要您没有将scaleFactor设置为10f,就不会重绘您的视图。
顺便说一句,我不明白为什么要将当前的比例因子乘以所选的比例因子。我建议将此作业更改为:
scaleFactor = detector.getScaleFactor();