【发布时间】:2019-02-10 05:57:16
【问题描述】:
我即将对包含文本的TextView 执行放大和缩小操作。我能够放大和缩小,但我需要使缩放功能更加平滑(比如在 Chrome 浏览器中缩放页面)。在执行放大和缩小操作(使用捏缩放方法)时,我正在以中心对齐的方式缩放文本内容,我想放大我正在放大的内容。
我附上我做的代码,请为我提出一个解决方案。
这是我的活动文件:
public class ZoomTextView extends TextView {
private static final String TAG = "ZoomTextView";
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
private float defaultSize;
private float zoomLimit = 3.0f;
public ZoomTextView(Context context) {
super(context);
initialize();
}
public ZoomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public ZoomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
private void initialize() {
defaultSize = getTextSize();
mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
/***
* @param zoomLimit
* Default value is 3, 3 means text can zoom 3 times the default size
*/
public void setZoomLimit(float zoomLimit) {
this.zoomLimit = zoomLimit;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent ev) {
super.onTouchEvent(ev);
mScaleDetector.onTouchEvent(ev);
return true;
}
/*Scale Gesture listener class,
mScaleFactor is getting the scaling value
and mScaleFactor is mapped between 1.0 and and zoomLimit
that is 3.0 by default. You can also change it. 3.0 means text
can zoom to 3 times the default value.*/
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, zoomLimit));
setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultSize * mScaleFactor);
Log.e(TAG, String.valueOf(mScaleFactor));
return true;
}
} }
这是我的 .xml 文件:
<noman.zoomtextview.ZoomTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="@string/sample_string"/> </RelativeLayout>
提前致谢。
【问题讨论】:
-
如果您对缩放有任何疑问,请告诉。
标签: java android textview zooming pinchzoom