я решил и полностью установить это обрезка и сохранение изображения с помощью 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);
}
}
} Я сделал изменения в этом классе в соответствии croping изображений и Setti нг растровых динамически
следующим является деятельность, которая использует некоторый вид в дизайне 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);
}
}
эта культура деятельность сохраняет обрезанное изображение во внутренней памяти, нажимая кнопку Готово
если возможно приложить скриншоты –
У меня есть экраны и описание, пожалуйста, посмотрите – user3269550
Возможный дубликат [Android: Free Croping of Image] (http://stackoverflow.com/questions/18439246/android-free-croping-of -image) –