申明:本文部分内容为网络相关资料整理,并结合本人实际工作总结而成。请引用或者转载注明出处,对于文章内容有疑问请留言。
一、功能简介
对于图片的裁剪操作,可能比较常见。但是在一些app中使用半透明裁剪框截图图片,用作头像,还如何实现呢?怎么把图片放在截取框的下面,以及怎么实现放大缩小后的截取呢?
二、构思
1.布局文件(片段)
<RelativeLayout
android:id="@+id/my_show_fragment_rl_clipBox"
android:layout_width="@dimen/my_show_fragment_tv_picture_width"
android:layout_height="@dimen/my_show_fragment_tv_picture_height"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/my_show_fragment_tv_picture_marginTop">
<RelativeLayout
android:id="@+id/my_show_fragment_rl_clip"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/my_show_fragment_iv_picture"
android:layout_width="@dimen/my_show_fragment_tv_picture_width"
android:layout_height="@dimen/my_show_fragment_tv_picture_height"/>
</RelativeLayout>
<View
android:id="@+id/my_show_fragment_v_clipBox"
android:layout_width="@dimen/my_show_fragment_tv_picture_width"
android:layout_height="@dimen/my_show_fragment_tv_picture_height"
android:background="@drawable/my_show_scale_box"/>
</RelativeLayout>
2.java代码(部分)
mShowFragmentXml = inflater.inflate(R.layout.my_show_fragment, container, false);
mClipRl = (RelativeLayout) mShowFragmentXml.findViewById(R.id.my_show_fragment_rl_clip);
mPhotoIv = (ImageView) view.findViewById(R.id.my_show_fragment_iv_picture);
ViewTreeObserver viewTreeObserver = mShowFragmentXml.getViewTreeObserver();
viewTreeObserver.addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
@Override
public void onWindowFocusChanged(final boolean hasFocus) {
if (hasFocus) {
int layoutWidth = mClipRl.getWidth();
int layoutHeight = mClipRl.getHeight();
int imgWidth = bitmap.getWidth();
int imgHeight = bitmap.getHeight();
int selectWidth = mClipView.getWidth();
int selectHeight = mClipView.getHeight();
//缩放比例
float scaleNum;
//将要裁剪的图片长宽高做对比, 将较小的一方做等比缩放成裁剪框大小
if (imgWidth < imgHeight) {
scaleNum = (selectWidth * 1.0f) / (imgWidth * 1.0f);
imgWidth = selectWidth;
imgHeight = (int) (scaleNum * imgHeight);
} else {
scaleNum = (selectHeight * 1.0f) / (imgHeight * 1.0f);
imgWidth = (int) (scaleNum * imgWidth);
imgHeight = selectHeight;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleNum, scaleNum);
//平移距离
matrix.postTranslate((layoutWidth - imgWidth) / 2, (layoutHeight - imgHeight) / 2);
mTop = (layoutHeight - selectHeight) / 2;
mLeft = (layoutWidth - selectWidth) / 2;
//设置缩放类型为矩阵
mPhotoIv.setScaleType(ImageView.ScaleType.MATRIX);
mPhotoIv.setImageMatrix(matrix);
mPhotoIv.setImageBitmap(bitmap);
}
}
});
mPhotoIv.setImageBitmap(bitmap);
mPhotoIv.setOnTouchListener(this);
mClipView = mShowFragmentXml.findViewById(R.id.my_show_fragment_v_clipBox);
3.解析
1)对整个布局进行窗口焦点监听,图片缩放移动之后的大小计算放在里面。
2)id为my_show_fragment_v_clipBox 的view是半透明截取框,此截取框长宽固定。
3)计算缩放比例以及移动距离,显示新的图片。
本文介绍了一种在Android应用中实现半透明裁剪框的方法,通过调整图片大小以适应固定尺寸的裁剪框,同时保持图片比例不变。具体包括布局文件设计、Java代码实现及关键步骤解析。
1786

被折叠的 条评论
为什么被折叠?



