Android怎么实现手势划定区域裁剪图片

Android怎么实现手势划定区域裁剪图片

这篇文章主要介绍“Android怎么实现手势划定区域裁剪图片”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Android怎么实现手势划定区域裁剪图片”文章能帮助大家解决问题。

Android怎么实现手势划定区域裁剪图片

需求:

拍照,然后对图片进行处理,划定矩形区域,将矩形区域裁剪下来

思路:

1、使用系统相机拍照,拍完返回,对图片进行压缩和存储。

2、新建一个activity处理图片裁剪,利用自定义view在画布上画出矩形区域。

3、根据坐标信息生成裁剪图片并存储。

部分核心代码:

1、调用系统相机拍照

StringIMAGE_PATH=Environment.getExternalStorageDirectory().getPath()+"/com.kwmax.demo/Image/";Stringfilename="xxxxxx.jpeg";FilepicFile=newFile(IMAGE_PATH+filename);if(!picFile.exists()){picFile.createNewFile();}...if(getContext().getPackageManager().getLaunchIntentForPackage("com.sec.android.app.camera")!=null){cameraIntent.setPackage("com.sec.android.app.camera");}if(getContext().getPackageManager().getLaunchIntentForPackage("com.android.hwcamera")!=null){cameraIntent.setPackage("com.android.hwcamera");}if(getContext().getPackageManager().getLaunchIntentForPackage("com.zte.camera")!=null){cameraIntent.setPackage("com.zte.camera");}cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//默认系统相机cameraIntent.addCategory("android.intent.category.DEFAULT");UripictureUri=Uri.fromFile(picFile);cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);startActivityForResult(intent,CAMERA_REQUEST_CODE);

2、自定义手势矩形view

publicclassCaptureRectViewextendsView{privateintx;privateinty;privateintm;privateintn;privatebooleansign;//绘画标记位privatePaintpaint;//画笔publicCaptureRectView(Contextcontext){super(context);paint=newPaint(Paint.FILTER_BITMAP_FLAG);}@OverrideprotectedvoidonDraw(Canvascanvas){if(sign){paint.setColor(Color.TRANSPARENT);}else{paint.setColor(Color.RED);paint.setAlpha(80);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(15f);canvas.drawRect(newRect(x,y,m,n),paint);}super.onDraw(canvas);}publicvoidsetSeat(intx,inty,intm,intn){this.x=x;this.y=y;this.m=m;this.n=n;}publicbooleanisSign(){returnsign;}publicvoidsetSign(booleansign){this.sign=sign;}}

3、裁剪页面布局

<?xmlversion="1.0"encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/drawrect_framelayout"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@color/black"android:clickable="true"android:orientation="vertical"><RelativeLayoutandroid:id="@+id/drawrect_relativelayout"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@color/black"android:orientation="vertical"><FrameLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_above="@+id/bottom"><LinearLayoutandroid:id="@+id/image_zoom_view_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_centerInParent="true"android:gravity="center"android:orientation="vertical"/><ImageViewandroid:id="@+id/capture_preview"android:layout_width="80dp"android:layout_height="80dp"/></FrameLayout><LinearLayoutandroid:id="@+id/bottom"android:layout_width="fill_parent"android:layout_height="50dip"android:layout_alignParentBottom="true"android:orientation="horizontal"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"><Buttonandroid:id="@+id/btn_capture"android:layout_width="50dp"android:layout_height="wrap_content"android:layout_weight="1"android:layout_marginRight="10dp"android:text="裁剪"/><Buttonandroid:id="@+id/btn_cancel"android:layout_width="50dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="取消"/></LinearLayout></RelativeLayout></FrameLayout>

4、裁剪activity

publicclassDrawRectActivityextendsBasicActivityimplementsOnClickListener,View.OnTouchListener{privateStringTAG="DrawRectActivity";privateStringimageString;privateStringimagePath;privateArrayList<String>imageList=null;privateintposition=0;privateintwidth,height;privateLinearLayoutlayerViewLayout=null;privateImageViewaiPreview;privateCaptureRectViewcaptureView;//绘画选择区域privateintcapX;//绘画开始的横坐标privateintcapY;//绘画开始的纵坐标privateintcapM;//绘画结束的横坐标privateintcapN;//绘画结束的纵坐标privateBitmapcaptureBitmap;privateButtoncancel;privateButtonaiCapture;privateFrameLayoutframeLayout;privateRelativeLayoutrelativeLayout;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);init();initUI();}privatevoidinit(){width=ImageUtils.getScreenWidth(this);height=ImageUtils.getScreenHeight(this);Intentintent=this.getIntent();Bundlebundle=intent.getExtras();imageString=bundle.getString("imageString");imagePath=bundle.getString("imagePath");position=bundle.getInt("position");imageList=parseImageString(imagePath,imageString);}@TargetApi(Build.VERSION_CODES.JELLY_BEAN)privatevoidinitUI(){setContentView(R.layout.draw_image_rect_view);frameLayout=(FrameLayout)findViewById(R.id.drawrect_framelayout);relativeLayout=(RelativeLayout)findViewById(R.id.drawrect_relativelayout);layerViewLayout=(LinearLayout)this.findViewById(R.id.image_zoom_view_layout);btncancel=(Button)findViewById(R.id.btn_cancel);btnCapture=(Button)findViewById(R.id.btn_capture);btnPreview=(ImageView)findViewById(R.id.capture_preview);ImageVieworiginImage=newImageView(this);Bitmapimage=ImageUtils.getBitmapFromFile(imagePath+imageList.get(position),1);originImage.setImageBitmap(image);originImage.setLayerType(View.LAYER_TYPE_SOFTWARE,null);layerViewLayout.addView(originImage,newLinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));captureView=newCaptureRectView(this);originImage.setOnTouchListener(this);this.addContentView(captureView,newViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));if(frameLayout.isClickable()){frameLayout.setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){}});}btncancel.setOnClickListener(this);btnCapture.setOnClickListener(this);}privateArrayList<String>parseImageString(StringimagePath,StringimageString){ArrayList<String>list=newArrayList<String>();StringallFiles=imageString.substring(imageString.indexOf("img://")+"img://".length());StringfileName=null;while(allFiles.indexOf(";")>0){fileName=allFiles.substring(0,allFiles.indexOf(";"));allFiles=allFiles.substring(allFiles.indexOf(";")+1);if(checkIsImageFile(fileName)&&newFile(imagePath+fileName).exists()){list.add(fileName);Log.v("ParseImageString()","imageName="+fileName);}else{Log.v("ParseImageString()","badimageName="+fileName);}}Log.v("ParseImageString()","imagelist.size="+list.size());returnlist;}/***判断是否相应的图片格式*/privatebooleancheckIsImageFile(StringfName){booleanisImageFormat;if(fName.endsWith(".jpg")||fName.endsWith(".gif")||fName.endsWith(".png")||fName.endsWith(".jpeg")||fName.endsWith(".bmp")){isImageFormat=true;}else{isImageFormat=false;}returnisImageFormat;}@OverridepublicbooleanonTouch(Viewview,MotionEventevent){switch(event.getAction()){caseMotionEvent.ACTION_DOWN:capX=0;capY=0;width=0;height=0;capX=(int)event.getX();capY=(int)event.getY();break;caseMotionEvent.ACTION_MOVE:capM=(int)event.getX();capN=(int)event.getY();captureView.setSeat(capX,capY,capM,capN);captureView.postInvalidate();break;caseMotionEvent.ACTION_UP:if(event.getX()>capX){width=(int)event.getX()-capX;}else{width=(int)(capX-event.getX());capX=(int)event.getX();}if(event.getY()>capY){height=(int)event.getY()-capY;}else{height=(int)(capY-event.getY());capY=(int)event.getY();}captureBitmap=getCapturePreview(this);if(null!=captureBitmap){btnPreview.setImageBitmap(captureBitmap);}break;}if(captureView.isSign()){returnfalse;}else{returntrue;}}privateBitmapgetCapturePreview(Activityactivity){Viewview=activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmapbitmap=view.getDrawingCache();Rectframe=newRect();activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);inttoHeight=frame.top;//todo:这里需要针对部分机型做适配if(width>0&&height>0){bitmap=Bitmap.createBitmap(bitmap,capX,capY+240,width,height);view.setDrawingCacheEnabled(false);returnbitmap;}else{returnnull;}}@OverridepublicvoidonClick(Viewv){switch(v.getId()){caseR.id.btn_cancel:Intentcancelintent=getIntent();createPendingResult(600,cancelintent,PendingIntent.FLAG_UPDATE_CURRENT);setResult(RESULT_OK,cancelintent);finish();break;caseR.id.btn_capture:Intentsureintent=getIntent();createPendingResult(CpAIphotoAttributes.PHOTO_CAPTURE,sureintent,PendingIntent.FLAG_UPDATE_CURRENT);if(captureBitmap!=null){try{Stringfile=IMAGE_PATH;Stringrandomid=UUID.randomUUID().toString();Stringfilename=randomid+".jpeg";FileOutputStreamfout=newFileOutputStream(file+filename);captureBitmap.compress(Bitmap.CompressFormat.JPEG,100,fout);sureintent.putExtra("capturePath",file+filename);sureintent.putExtra("capturefilename",filename);sureintent.putExtra("capturefileid",randomid);}catch(FileNotFoundExceptione){e.printStackTrace();}}setResult(RESULT_OK,sureintent);finish();break;default:break;}}@OverridepublicbooleanonKeyDown(intkeyCode,KeyEventevent){switch(keyCode){caseKeyEvent.KEYCODE_BACK:Intentcancelintent=getIntent();createPendingResult(600,cancelintent,PendingIntent.FLAG_UPDATE_CURRENT);cancelintent.putExtra("imagePath",imagePath);cancelintent.putExtra("position",position);cancelintent.putExtra("todowhat","cancel");setResult(RESULT_OK,cancelintent);finish();break;default:break;}returnfalse;}@Overridepublicvoidfinish(){super.finish();}@OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){if(resultCode==RESULT_OK){switch(requestCode){case400:Stringtext=null;Log.v("DrawRectActivity","onActivityReaultimagePath="+imagePath+imageList.get(position));if(StringUtil.isNotBlank(text)){Log.v("DrawRectActivity","onActivityReaultimagePath="+imagePath+imageList.get(position)+";text="+text);}else{}break;default:break;}}super.onActivityResult(requestCode,resultCode,data);}@OverrideprotectedvoidonDestroy(){super.onDestroy();}}

关于“Android怎么实现手势划定区域裁剪图片”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注恰卡编程网行业资讯频道,小编每天都会为大家更新不同的知识点。

发布于 2022-05-19 10:36:33
收藏
分享
海报
0 条评论
19
上一篇:Python中怎么添加搜索路径 下一篇:怎么使用pytorch读取数据集
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码