如何裁剪位图里面的片段? [英] How to Crop Bitmap inside Fragment?

查看:176
本文介绍了如何裁剪位图里面的片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助解决这个问题...

第一块碎片
在这里,这是一个1stFragment文件发送的字符串连接codeD位图

  TMP = getArguments()的getString(PHOTO)。      字节[] EN codeByte = Base64.de code(TMP,Base64.DEFAULT);
      BMP = BitmapFactory.de codeByteArray的(EN codeByte,0,EN codeByte.length);      ByteArrayOutputStream B =新ByteArrayOutputStream();
      bmp.com preSS(Bitmap.Com pressFormat.PNG,100,B);
      BM = b.toByteArray();
      临时= Base64.en codeToString(BM,Base64.DEFAULT);片段FR =新CropToolActivity();
                        FM = getFragmentManager();
                        FragmentTransaction英尺= fm.beginTransaction();
                        ARGS =新包();
                        args.putString(PHOTO,温度);
                        fr.setArguments(参数);
                        ft.replace(R.id.frame,FR);
                        ft.commit();

CropToolActivity
这儿,这是一个2ndFragment文件接收的字符串连接codeD位图
也设置CropView TI布局

 公开查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){
        查看查看= inflater.inflate(R.layout.croptool,集装箱,FALSE);        myCropView =(CropView)view.findViewById(R.id.crop_tool);
        myCropView =新CropView(getActivity()getApplicationContext());        TMP = getArguments()的getString(PHOTO)。        字节[] EN codeByte = Base64.de code(TMP,Base64.DEFAULT);
        BMP = BitmapFactory.de codeByteArray的(EN codeByte,0,EN codeByte.length);
        myCropView.setImageBitmap(BMP);

croptool.xml
这是第二个片段布局的XML文件
    
    

 < com.tcss.photostyle.CropView
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =match_parent
        机器人:ID =@ + ID / crop_tool/>< / LinearLayout中>

CropView.Java

这里,这是一个croptool的Java文件以证明对位图Croptool

 公共类CropView扩展了ImageView的{涂料粉刷=新的油漆();
私人INT initial_size = 300;
私人静点leftTop,rightBottom,中心,previous;私有静态最终诠释DRAG = 0;
私有静态最终诠释LEFT = 1;
私有静态最终诠释TOP = 2;
私有静态最终诠释RIGHT = 3;
私有静态最终诠释BOTTOM = 4;私人诠释imageScaledWidth,imageScaledHeight;
//添加父类的构造函数
公共CropView(上下文的背景下){
   超级(上下文);
   initCropView();
 } 公共CropView(上下文的背景下,ATTRS的AttributeSet){
   超级(上下文,ATTRS,0);
   initCropView();
 } 公共CropView(上下文的背景下,ATTRS的AttributeSet,诠释defStyle){
  超(背景下,ATTRS,defStyle);
  initCropView();
 } @覆盖
 保护无效的onDraw(帆布油画)
 {
   super.onDraw(画布);
   如果(leftTop.equals(0,0))
      resetPoints();
  canvas.drawRect(leftTop.x,leftTop.y,rightBottom.x,rightBottom.y,油漆);
  } @覆盖
 公共布尔onTouchEvent(MotionEvent事件){
  INT eventaction = event.getAction();
  开关(eventaction){
      案例MotionEvent.ACTION_DOWN:
          previous.set((int)的event.getX(),(INT)event.getY());
          打破;
     案例MotionEvent.ACTION_MOVE:
         如果(isActionInsideRectangle(event.getX(),event.getY())){
             adjustRectangle((int)的event.getX(),(INT)event.getY());
             无效(); //重绘矩形
             previous.set((int)的event.getX(),(INT)event.getY());
         }
         打破;
     案例MotionEvent.ACTION_UP:
         previous =新点();
         打破;
 }
  返回true;
 } 私人无效initCropView(){
  paint.setColor(Color.YELLOW);
  paint.setStyle(Style.STROKE);
  paint.setStrokeWidth(5);
  leftTop =新点();
 rightBottom =新点();
 中心=新点();
 previous =新点();
 }公共无效resetPoints(){
   center.set(的getWidth()/ 2,的getHeight()/ 2);
   leftTop.set((的getWidth() - initial_size)/ 2,(的getHeight() - initial_size)/ 2);
   rightBottom.set(leftTop.x + initial_size,leftTop.y + initial_size);
 } 私有静态布尔isActionInsideRectangle(浮法X,浮法Y){
  INT缓冲区= 10;
  则返回(x> =(leftTop.x缓冲器)及&放大器; X&下; =(rightBottom.x +缓冲)及&放大器y与其所连接; =(leftTop.y缓冲器)及&放大器; Y&下; =(rightBottom。 Y +缓冲))真:假;?
 } 私人布尔isInImageRange(点的PointF){
  //获取图像矩阵值,并把它们放在一个数组
  浮动[] F =新的浮动[9];
 。getImageMatrix()的GetValues​​(F); //计算缩放尺寸
  imageScaledWidth = Math.round(getDrawable()getIntrinsicWidth()* F [Matrix.MSCALE_X]);
  imageScaledHeight = Math.round(getDrawable()getIntrinsicHeight()* F [Matrix.MSCALE_Y]);  返回(point.x>=(center.x-(imageScaledWidth/2))&&point.x<=(center.x+(imageScaledWidth/2))&&point.y>=(center.y-(imageScaledHeight/2))&&point.y<=(center.y+(imageScaledHeight/2)))?true:false;
} 私人无效adjustRectangle(INT X,int y)对{
  INT运动;
  开关(getAffectedSide(X,Y)){
      案例LEFT:
         运动= X-leftTop.x;
         如果(isInImageRange(新的PointF(leftTop.x +运动,leftTop.y +运动)))
            leftTop.set(leftTop.x +运动,leftTop.y +运动);
        打破;
      案例TOP:
        运动= Y-leftTop.y;
        如果(isInImageRange(新的PointF(leftTop.x +运动,leftTop.y +运动)))
            leftTop.set(leftTop.x +运动,leftTop.y +运动);
        打破;
      案例RIGHT:
        运动= X-rightBottom.x;
        如果(isInImageRange(新的PointF(rightBottom.x +运动,rightBottom.y +运动)))
            rightBottom.set(rightBottom.x +运动,rightBottom.y +运动);
        打破;
     案例BOTTOM:
        运动= Y-rightBottom.y;
        如果(isInImageRange(新的PointF(rightBottom.x +运动,rightBottom.y +运动)))
            rightBottom.set(rightBottom.x +运动,rightBottom.y +运动);
        打破;
     案例DRAG:
        移动= X-previous.x;
        INT movementY = Y- previous.y;
        如果(isInImageRange(新的PointF(leftTop.x +运动,leftTop.y + movementY))及&放大器; isInImageRange(新的PointF(rightBottom.x +运动,rightBottom.y + movementY))){
            leftTop.set(leftTop.x +运动,leftTop.y + movementY);
              rightBottom.set(rightBottom.x +运动,rightBottom.y + movementY);
        }
        打破;
  }
}  私有静态诠释getAffectedSide(浮法X,浮法Y){
   INT缓冲区= 10;
   如果(X GT; =(leftTop.x缓冲器)及&放大器; X&下; =(leftTop.x +缓冲))
    返回LEFT;
   否则如果(γ&GT; =(leftTop.y缓冲器)及&放大器; Y&下; =(leftTop.y +缓冲))
    返回TOP;
   否则如果(X GT; =(rightBottom.x缓冲器)及&放大器; X&下; =(rightBottom.x +缓冲))
    返回的权利;
   否则如果(γ&GT; =(rightBottom.y缓冲器)及&放大器; Y&下; =(rightBottom.y +缓冲))
    回到BOTTOM;
    其他
     返回DRAG;
   }   公众的byte [] getCroppedImage(){
   BitmapDrawable绘制=(BitmapDrawable)getDrawable();
   浮X = leftTop.x-center.x +(drawable.getBitmap()的getWidth()/ 2);
   浮Y = leftTop.y-center.y +(drawable.getBitmap()的getHeight()/ 2);
   位图裁剪= Bitmap.createBitmap(drawable.getBitmap(),(int)x,(int)y,(int)rightBottom.x-(int)leftTop.x,(int)rightBottom.y-(int)leftTop.y);
 ByteArrayOutputStream流=新ByteArrayOutputStream();
 cropped.com preSS(Bitmap.Com pressFormat.PNG,100,流);
  返回stream.toByteArray();
  }
 }


解决方案

下面是从中心裁剪位图的方法,假设 newWidth&LT; bitmap.getWidth()和newHeight&下; bitmap.getHeight()

 公共位图cropBitmap(位图位图,诠释newWidth,诠释newHeight){
        双X =(bitmap.getWidth() - newWidth)/ 2;
        双Y =(bitmap.getHeight() - newHeight)/ 2;        位图B = Bitmap.createBitmap((INT)newWidth,(INT)newHeight,Bitmap.Config.ARGB_8888);
        帆布C =新的Canvas(B);
        c.drawBitmap(位图,新的Rect((int)的X,(INT)Y,(INT)(X + newWidth),(INT)(Y + newHeight)),新的Rect(0,0,(INT)newWidth, (INT)newHeight),NULL);
        返回b;
    }

Please Help to solve this problem...

First Fragment Here this is a 1stFragment file sends the string of encoded bitmap

    tmp = getArguments().getString("PHOTO");

      byte [] encodeByte=Base64.decode(tmp,Base64.DEFAULT);
      bmp=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);

      ByteArrayOutputStream b=new  ByteArrayOutputStream();
      bmp.compress(Bitmap.CompressFormat.PNG,100, b);
      bm =b.toByteArray();
      temp=Base64.encodeToString(bm, Base64.DEFAULT);Fragment fr = new CropToolActivity();
                        fm = getFragmentManager();
                        FragmentTransaction ft = fm.beginTransaction();
                        args = new Bundle();
                        args.putString("PHOTO", temp);
                        fr.setArguments(args);
                        ft.replace(R.id.frame,fr);
                        ft.commit();

CropToolActivity Here this is a 2ndFragment file receives the string of encoded bitmap also set the CropView ti the layout

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.croptool, container, false);

        myCropView = (CropView)view.findViewById(R.id.crop_tool);
        myCropView = new CropView(getActivity().getApplicationContext());

        tmp = getArguments().getString("PHOTO");

        byte [] encodeByte=Base64.decode(tmp,Base64.DEFAULT);
        bmp=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        myCropView.setImageBitmap(bmp);

croptool.xml This is a XML file for 2nd Fragment layout

    <com.tcss.photostyle.CropView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:id="@+id/crop_tool" />

</LinearLayout>

CropView.Java

Here this is a croptool java file to demonstrate the Croptool on bitmap

public class CropView extends ImageView {

Paint paint = new Paint();
private int initial_size = 300;
private static Point leftTop, rightBottom, center, previous;

private static final int DRAG= 0;
private static final int LEFT= 1;
private static final int TOP= 2;
private static final int RIGHT= 3;
private static final int BOTTOM= 4;

private int imageScaledWidth,imageScaledHeight;
// Adding parent class constructors   
public CropView(Context context) {
   super(context);
   initCropView();
 }

 public CropView(Context context, AttributeSet attrs) {
   super(context, attrs, 0);
   initCropView();
 }

 public CropView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  initCropView();
 }

 @Override
 protected void onDraw(Canvas canvas)
 {
   super.onDraw(canvas);
   if(leftTop.equals(0, 0))
      resetPoints();
  canvas.drawRect(leftTop.x, leftTop.y, rightBottom.x, rightBottom.y, paint);
  }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  int eventaction = event.getAction();
  switch (eventaction) { 
      case MotionEvent.ACTION_DOWN:
          previous.set((int)event.getX(), (int)event.getY());
          break; 
     case MotionEvent.ACTION_MOVE: 
         if(isActionInsideRectangle(event.getX(), event.getY())) {
             adjustRectangle((int)event.getX(), (int)event.getY());
             invalidate(); // redraw rectangle
             previous.set((int)event.getX(), (int)event.getY());
         }
         break; 
     case MotionEvent.ACTION_UP: 
         previous = new Point();
         break;
 }         
  return true;
 }

 private void initCropView() {
  paint.setColor(Color.YELLOW);
  paint.setStyle(Style.STROKE);
  paint.setStrokeWidth(5);  
  leftTop = new Point();
 rightBottom = new Point();
 center = new Point();
 previous = new Point();
 }

public void resetPoints() {
   center.set(getWidth()/2, getHeight()/2);
   leftTop.set((getWidth()-initial_size)/2,(getHeight()-initial_size)/2);
   rightBottom.set(leftTop.x+initial_size, leftTop.y+initial_size);
 }

 private static boolean isActionInsideRectangle(float x, float y) {
  int buffer = 10;
  return (x>=(leftTop.x-buffer)&&x<=(rightBottom.x+buffer)&& y>=(leftTop.y-buffer)&&y<=(rightBottom.y+buffer))?true:false;
 }

 private boolean isInImageRange(PointF point) {
  // Get image matrix values and place them in an array
  float[] f = new float[9];
 getImageMatrix().getValues(f);

 // Calculate the scaled dimensions
  imageScaledWidth = Math.round(getDrawable().getIntrinsicWidth() * f[Matrix.MSCALE_X]);
  imageScaledHeight = Math.round(getDrawable().getIntrinsicHeight() * f[Matrix.MSCALE_Y]);

  return (point.x>=(center.x-(imageScaledWidth/2))&&point.x<=(center.x+(imageScaledWidth/2))&&point.y>=(center.y-(imageScaledHeight/2))&&point.y<=(center.y+(imageScaledHeight/2)))?true:false;
}

 private void adjustRectangle(int x, int y) {
  int movement;
  switch(getAffectedSide(x,y)) {
      case LEFT:
         movement = x-leftTop.x;
         if(isInImageRange(new  PointF(leftTop.x+movement,leftTop.y+movement)))
            leftTop.set(leftTop.x+movement,leftTop.y+movement);
        break;
      case TOP:
        movement = y-leftTop.y;
        if(isInImageRange(new PointF(leftTop.x+movement,leftTop.y+movement)))
            leftTop.set(leftTop.x+movement,leftTop.y+movement);
        break;
      case RIGHT:
        movement = x-rightBottom.x;
        if(isInImageRange(new PointF(rightBottom.x+movement,rightBottom.y+movement)))
            rightBottom.set(rightBottom.x+movement,rightBottom.y+movement);
        break;
     case BOTTOM:
        movement = y-rightBottom.y;
        if(isInImageRange(new PointF(rightBottom.x+movement,rightBottom.y+movement)))
            rightBottom.set(rightBottom.x+movement,rightBottom.y+movement);
        break;      
     case DRAG:
        movement = x-previous.x;
        int movementY = y-previous.y;
        if(isInImageRange(new PointF(leftTop.x+movement,leftTop.y+movementY)) && isInImageRange(new PointF(rightBottom.x+movement,rightBottom.y+movementY))) {
            leftTop.set(leftTop.x+movement,leftTop.y+movementY);
              rightBottom.set(rightBottom.x+movement,rightBottom.y+movementY);
        }
        break;
  }
}

  private static int getAffectedSide(float x, float y) {
   int buffer = 10;
   if(x>=(leftTop.x-buffer)&&x<=(leftTop.x+buffer))
    return LEFT;
   else if(y>=(leftTop.y-buffer)&&y<=(leftTop.y+buffer))
    return TOP;
   else if(x>=(rightBottom.x-buffer)&&x<=(rightBottom.x+buffer))
    return RIGHT;
   else if(y>=(rightBottom.y-buffer)&&y<=(rightBottom.y+buffer))
    return BOTTOM;
    else
     return DRAG;
   }

   public byte[] getCroppedImage() {
   BitmapDrawable drawable = (BitmapDrawable)getDrawable();
   float x = leftTop.x-center.x+(drawable.getBitmap().getWidth()/2);
   float y = leftTop.y-center.y+(drawable.getBitmap().getHeight()/2);
   Bitmap cropped = Bitmap.createBitmap(drawable.getBitmap(),(int)x,(int)y,(int)rightBottom.x-(int)leftTop.x,(int)rightBottom.y-(int)leftTop.y);
 ByteArrayOutputStream stream = new ByteArrayOutputStream();
 cropped.compress(Bitmap.CompressFormat.PNG, 100, stream);
  return stream.toByteArray();
  }
 }

解决方案

Here is a method for cropping bitmap from center, assume that newWidth < bitmap.getWidth() and newHeight < bitmap.getHeight()

    public Bitmap cropBitmap(Bitmap bitmap, int newWidth, int newHeight) {
        double x = (bitmap.getWidth() - newWidth) / 2;
        double y = (bitmap.getHeight() - newHeight) / 2;

        Bitmap b = Bitmap.createBitmap((int)newWidth, (int)newHeight, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        c.drawBitmap(bitmap, new Rect((int)x , (int)y, (int)(x + newWidth), (int)(y + newHeight)), new Rect(0, 0, (int)newWidth, (int)newHeight), null);
        return b;
    }

这篇关于如何裁剪位图里面的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆