android自定义图片裁剪
时间: 2023-08-31 10:09:51 浏览: 170
Android中自定义图片裁剪可以通过使用自定义View和Bitmap对象来实现。以下是一些步骤:
1. 创建自定义View类,继承自View类。在onDraw()方法中绘制Bitmap对象。
2. 设置触摸事件,获取用户手指操作的坐标,计算出裁剪区域的左上角和右下角坐标。
3. 在onTouchEvent()方法中重绘View,绘制裁剪后的Bitmap对象。
4. 使用Matrix对象进行缩放和旋转操作。
下面是一个简单的示例代码:
```
public class CropImageView extends View {
private Bitmap mBitmap;
private Paint mPaint;
private Rect mRect;
private Matrix mMatrix;
private float mStartX;
private float mStartY;
private float mEndX;
private float mEndY;
public CropImageView(Context context) {
super(context);
init();
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.RED);
mRect = new Rect();
mMatrix = new Matrix();
}
public void setImageBitmap(Bitmap bitmap) {
mBitmap = bitmap;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, mMatrix, null);
}
canvas.drawRect(mRect, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartX = event.getX();
mStartY = event.getY();
mEndX = mStartX;
mEndY = mStartY;
break;
case MotionEvent.ACTION_MOVE:
mEndX = event.getX();
mEndY = event.getY();
break;
case MotionEvent.ACTION_UP:
mEndX = event.getX();
mEndY = event.getY();
break;
}
calculateRect();
invalidate();
return true;
}
private void calculateRect() {
float left = Math.min(mStartX, mEndX);
float top = Math.min(mStartY, mEndY);
float right = Math.max(mStartX, mEndX);
float bottom = Math.max(mStartY, mEndY);
mRect.set((int) left, (int) top, (int) right, (int) bottom);
float centerX = (left + right) / 2;
float centerY = (top + bottom) / 2;
mMatrix.reset();
mMatrix.postTranslate(-centerX, -centerY);
mMatrix.postRotate(45);
mMatrix.postScale(0.5f, 0.5f);
mMatrix.postTranslate(centerX, centerY);
}
}
```
这个示例代码实现了一个简单的图片裁剪功能,并在裁剪后对图片进行了缩放和旋转。你可以根据自己的需求修改代码。
阅读全文