大家好我正在使用FlexiCrop 并且正在裁剪不规则形状的图像我的活动代码看起来像这样
public class CropActivity
extends Activity implements OnTouchListener {
private Uri mImageCaptureUri;
private ImageView drawImageView;
private Bitmap sourceBitmap;
private Path clipPath;
private static final int PICK_FROM_FILE = 1;
private static final int CAMERA_CAPTURE = 2;
Bitmap bmp;
Bitmap alteredBitmap;
Canvas canvas;
Paint paint;
Matrix matrix;
float downx = 0;
float downy = 0;
float upx = 0;
float upy = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crop);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException e){
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
Button saveButton = (Button) findViewById(R.id.btn_save);
Button discardButton = (Button) findViewById(R.id.btn_discard);
drawImageView = (ImageView) findViewById(R.id.DrawImageView);
drawImageView.setOnTouchListener(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, String.valueOf(Math.round(Math.random()*100000))+".jpg");
fOut = new FileOutputStream(file);
alteredBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
AlertDialog.Builder builder = new AlertDialog.Builder(StickersCreator.this);
builder.setMessage("Saved");
AlertDialog dialog = builder.create();
dialog.show();
//Now deleting the temporary file created on camera capture
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
f.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
discardButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mImageCaptureUri != null) {
//Now deleting the temporary file created on camera capture
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
f.delete();
}
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
//resetting the image view
ImageView iv = (ImageView) findViewById(R.id.DrawImageView);
iv.setImageDrawable(null);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CAMERA_CAPTURE:
mImageCaptureUri = data.getData();
doCrop();
break;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
clipPath = new Path();
clipPath.moveTo(downx, downy);
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
clipPath.lineTo(upx, upy);
drawImageView.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
clipPath.lineTo(upx, upy);
drawImageView.invalidate();
cropImageByPath();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
private void cropImageByPath() {
//closing the path now.
clipPath.close();
//setting the fill type to inverse, so that the outer part of the selected path gets filled.
clipPath.setFillType(FillType.INVERSE_WINDING);
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.BLACK);
canvas.drawPath(clipPath, xferPaint);
xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(alteredBitmap, 0, 0, xferPaint);
}
private void doCrop() {
try {
sourceBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
mImageCaptureUri), null, bmpFactoryOptions);
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
mImageCaptureUri), null, bmpFactoryOptions);
alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
.getHeight(), bmp.getConfig());
canvas = new Canvas(alteredBitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
//loading the image bitmap in image view
drawImageView.setImageBitmap(alteredBitmap);
//setting the touch listener
drawImageView.setOnTouchListener(this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
是裁剪图像,但是当我绘制用于裁剪形状绘制的形状从我触摸的地方的远处点开始绘制形状时,从我触摸到的视图中获取形状的上方,可以建议我在这里做错了什么
冷杉是原始图像,当我在键盘上绘制一个非常大的圆圈时,它会远离键盘和非常小的圆圈第二个图像。 我在键盘上钻了一个圆圈,但它从上面裁剪而且圆圈的尺寸非常小
答案 0 :(得分:2)
我已经使用Android: Free Croping of Image解决并完全设置了此裁剪和图像保存,并对我自己选择图像和在屏幕中拟合图像进行了一些修改,我的代码修改如下
public class SomeView extends View implements OnTouchListener {
private Paint paint;
public static List<Point> points;
int DIST = 2;
boolean flgPathDraw = true;
public Uri orignalUri;
float origianlheight=0.0f,originalwidth=0.0f,heightratio=0.0f,widthratio=0.0f;
public static int REQUEST_CODE=2;
Point mfirstpoint = null;
boolean bfirstpoint = false;
Point mlastpoint = null;
boolean cropflag=false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bg_crop);
Context mContext;
public void setBitmap(Bitmap bmp,Uri uri){
orignalUri=uri;
points = new ArrayList<Point>();
setFocusable(true);
setFocusableInTouchMode(true);
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bmp.getHeight();
originalwidth=bmp.getWidth();
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=bmp;
bitmap=Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth()*widthratio),(int)(bmp.getHeight()*heightratio), true);
// bitmap=bmp;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
flgPathDraw = true;
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
cropflag=false;
}
public void clear(){
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
flgPathDraw = true;
cropflag=false;
invalidate();
}
public SomeView(Context c) {
super(c);
mContext = c;
setFocusable(true);
setFocusableInTouchMode(true);
DisplayMetrics metrics = c.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bitmap.getHeight();
originalwidth=bitmap.getWidth();
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=Bitmap.createScaledBitmap(bitmap, (int)(originalwidth*widthratio),(int)(origianlheight*heightratio), true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
flgPathDraw = true;
cropflag=false;
}
public SomeView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setFocusable(true);
setFocusableInTouchMode(true);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
origianlheight=bitmap.getHeight();
originalwidth=bitmap.getWidth();
//if(origianlheight>originalwidth){
heightratio=height/origianlheight;
// }else{
widthratio=width/originalwidth;
// }
bitmap=Bitmap.createScaledBitmap(bitmap, (int)(originalwidth*widthratio),(int)(origianlheight*heightratio), true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
flgPathDraw = true;
cropflag=false;
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0,paint);
Path path = new Path();
boolean first = true;
for (int i = 0; i < points.size(); i += 2) {
Point point = points.get(i);
if (first) {
first = false;
path.moveTo(point.x, point.y);
} else if (i < points.size() - 1) {
Point next = points.get(i + 1);
path.quadTo(point.x, point.y, next.x, next.y);
} else {
mlastpoint = points.get(i);
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
// if(event.getAction() != MotionEvent.ACTION_DOWN)
// return super.onTouchEvent(event);
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
if (flgPathDraw) {
if (bfirstpoint) {
if (comparepoint(mfirstpoint, point)) {
// points.add(point);
points.add(mfirstpoint);
flgPathDraw = false;
// showcropdialog();
cropflag=true;
} else {
points.add(point);
}
} else {
points.add(point);
}
if (!(bfirstpoint)) {
mfirstpoint = point;
bfirstpoint = true;
}
}
invalidate();
Log.e("Hi ==>", "Size: " + point.x + " " + point.y);
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("Action up*******~~~~~~~>>>>", "called");
mlastpoint = point;
if (flgPathDraw) {
if (points.size() > 12) {
if (!comparepoint(mfirstpoint, mlastpoint)) {
flgPathDraw = false;
points.add(mfirstpoint);
// showcropdialog();
cropflag=true;
}
}
}
}
return true;
}
private boolean comparepoint(Point first, Point current) {
int left_range_x = (int) (current.x - 3);
int left_range_y = (int) (current.y - 3);
int right_range_x = (int) (current.x + 3);
int right_range_y = (int) (current.y + 3);
if ((left_range_x < first.x && first.x < right_range_x)
&& (left_range_y < first.y && first.y < right_range_y)) {
if (points.size() < 10) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public void fillinPartofPath() {
Point point = new Point();
point.x = points.get(0).x;
point.y = points.get(0).y;
points.add(point);
invalidate();
}
public void resetView() {
points.clear();
paint.setColor(Color.WHITE);
paint.setStyle(Style.STROKE);
flgPathDraw = true;
invalidate();
}
/* private void showcropdialog() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
// bfirstpoint = false;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
mContext.startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", false);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
mContext.startActivity(intent);
bfirstpoint = false;
// resetView();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Do you Want to save Crop or Non-crop image?")
.setPositiveButton("Crop", dialogClickListener)
.setNegativeButton("Non-crop", dialogClickListener).show()
.setCancelable(false);
}*/
public void Crop(){
if(cropflag){
Intent intent;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
intent.putExtra("heightratio", heightratio);
intent.putExtra("widthratio", widthratio);
intent.putExtra("URI", orignalUri.toString());
((Activity)mContext).startActivityForResult(intent,REQUEST_CODE);
}
}
} 我根据裁剪图像和动态设置位图在此类中进行了更改
接下来是在设计xml中使用某些视图的活动,如
public class StickersCreator
extends Activity{
ImageButton btnCapture,btnChooseFromlib,btnClear;
Button btnCrop;
SomeView someView;
private static final String RESULT_BUNDLE_EXTAS = "RESULT_BUNDLE_EXTAS";
private static final String RESULT_BUNDLE_DATA = "RESULT_BUNDLE_DATA";
private static final String RESULT_BUNDLE_REQUEST_CODE = "RESULT_BUNDLE_REQUEST_CODE";
private static final String RESULT_BUNDLE_RESULT_CODE = "RESULT_BUNDLE_RESULT_CODE";
private static final int REQUEST_PICK_IMAGE = 0;
private static final int REQUEST_CAPTURE_IMAGE = 1;
private static final int REQUEST_CROP=2;
private Uri captureImageUri;
private Bundle resultBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stickers_creator);
btnCrop=(Button)findViewById(R.id.btnCrop);
btnCapture=(ImageButton)findViewById(R.id.BtnCapture);
btnClear=(ImageButton)findViewById(R.id.btnClear);
btnChooseFromlib=(ImageButton)findViewById(R.id.btnChoosefromLib);
someView=(SomeView)findViewById(R.id.someView);
btnCrop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someView.Crop();
}
});
btnClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someView.clear();
}
});
btnCapture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageUri = null;
try {
String storageState = Environment.getExternalStorageState();
if (TextUtils.equals(storageState, Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separatorChar
+ "Android/data/"
+ getApplicationContext().getPackageName()
+ "/files/";
File directory = new File(path);
directory.mkdirs();
File file = new File(directory,
Integer.toHexString((int) System
.currentTimeMillis()) + ".jpg");
file.createNewFile();
captureImageUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureImageUri);
}
} catch (IOException e) {
if (BuildConfig.DEBUG) {
Log.w("FrameEditor",
"Can not create temp file for image capture "
+ e.getMessage());
}
}
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
});
btnChooseFromlib.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
resultBundle = new Bundle();
if (intent != null) {
Bundle extras = intent.getExtras();
resultBundle.putBundle(RESULT_BUNDLE_EXTAS, extras);
Uri uriData = intent.getData();
if (uriData != null) {
resultBundle.putParcelable(RESULT_BUNDLE_DATA, uriData);
}
}
resultBundle.putInt(RESULT_BUNDLE_REQUEST_CODE, requestCode);
resultBundle.putInt(RESULT_BUNDLE_RESULT_CODE, resultCode);
super.onActivityResult(requestCode, resultCode, intent);
handleActivityResult();
}
private void handleActivityResult() {
if (resultBundle == null) {
return;
}
int requestCode = resultBundle.getInt(RESULT_BUNDLE_REQUEST_CODE);
int resultCode = resultBundle.getInt(RESULT_BUNDLE_RESULT_CODE);
Uri dataUri = resultBundle.getParcelable(RESULT_BUNDLE_DATA);
switch (requestCode) {
case REQUEST_PICK_IMAGE: {
if (resultCode == RESULT_OK) {
if (dataUri != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(dataUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap1 = BitmapFactory.decodeFile(filePath, options);
Uri uri=Uri.fromFile(new File(filePath));
someView.setBitmap(bitmap1,uri);
// Intend for EditorActivity
}
}
break;
}
case REQUEST_CAPTURE_IMAGE: {
if (resultCode == RESULT_OK) {
if (captureImageUri != null) {
// Intend for EditorActivity
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), captureImageUri);
someView.setBitmap(bitmap,captureImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
case REQUEST_CROP:{
}
}
}
resultBundle = null;
}
}
此贴纸创建者活动允许用户清除裁剪并从媒体中选择图像或捕获图像然后裁剪图像
public class CropActivity extends Activity {
ImageView compositeImageView;
boolean crop;
Bitmap resultingImage;
Uri imageUri;
Button btnDone,btnCancel;
float heightratio=0.0f,widthratio=0.0f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
btnDone=(Button)findViewById(R.id.btnDone);
btnCancel=(Button)findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CropActivity.this, StickersCreator.class);
setResult(RESULT_CANCELED);
finish();
}
});
btnDone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int widthOfscreen = 0;
FileOutputStream out = null;
try {
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
File Filename=new File(getFilesDir(),ts+".png");
//File Filename1=new File(getFilesDir(),"EPICBATTLE"+((Long)(System.currentTimeMillis()/1000)).toString()+"_ico.png");
out = new FileOutputStream(Filename);
resultingImage.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(CropActivity.this, StickersCreator.class);
setResult(RESULT_OK);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
crop = extras.getBoolean("crop");
heightratio=extras.getFloat("heightratio");
widthratio=extras.getFloat("widthratio");
imageUri=Uri.parse(extras.getString("URI"));
// byte[] byteArray = getIntent().getByteArrayExtra("image");
// bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
int widthOfscreen = 0;
int heightOfScreen = 0;
DisplayMetrics dm = new DisplayMetrics();
try {
getWindowManager().getDefaultDisplay().getMetrics(dm);
} catch (Exception ex) {
}
widthOfscreen = dm.widthPixels;
heightOfScreen = dm.heightPixels;
compositeImageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap2=null;
try {
bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bitmap2=Bitmap.createScaledBitmap(bitmap2, (int)(bitmap2.getWidth()*widthratio),(int)(bitmap2.getHeight()*heightratio), true);
resultingImage = Bitmap.createBitmap(widthOfscreen,
heightOfScreen, bitmap2.getConfig());
// resultingImage=CropBitmapTransparency(resultingImage);
Canvas canvas = new Canvas(resultingImage);
Paint paint = new Paint();
paint.setAntiAlias(true);
Path path = new Path();
for (int i = 0; i < SomeView.points.size(); i++) {
path.lineTo(SomeView.points.get(i).x, SomeView.points.get(i).y);
}
canvas.drawPath(path, paint);
if (crop) {
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
} else {
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
}
canvas.drawBitmap(bitmap2, 0, 0, paint);
resultingImage=CropBitmapTransparency(resultingImage);
compositeImageView.setImageBitmap(resultingImage);//setImageBitmap(resultingImage);
}
Bitmap CropBitmapTransparency(Bitmap sourceBitmap){
int minX = sourceBitmap.getWidth();
int minY = sourceBitmap.getHeight();
int maxX = -1;
int maxY = -1;
for(int y = 0; y < sourceBitmap.getHeight(); y++)
{
for(int x = 0; x < sourceBitmap.getWidth(); x++)
{
int alpha = (sourceBitmap.getPixel(x, y) >> 24) & 255;
if(alpha > 0) // pixel is not 100% transparent
{
if(x < minX)
minX = x;
if(x > maxX)
maxX = x;
if(y < minY)
minY = y;
if(y > maxY)
maxY = y;
}
}
}
if((maxX < minX) || (maxY < minY))
return null; // Bitmap is entirely transparent
// crop bitmap to non-transparent area and return:
return Bitmap.createBitmap(sourceBitmap, minX, minY, (maxX - minX) + 1, (maxY - minY) + 1);
}
}
此裁剪活动会在按下完成按钮的同时将裁剪后的图像保存在内存中