안드로이드 개발 질문/답변
(글 수 45,052)
CropImageActivity 에서 CropImage를 이용합니다. 여기서 아래쪽으로 주석으로 설명을
/////////////////////////////////////////////
public class CropImageActivity extends Activity implements OnClickListener {
CropImage ci;
String path;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 화면 계속 켜지게
setContentView(R.layout.crop_image);
Intent intent = getIntent();
String imgpath =intent.getStringExtra("imgpath"); //전클래스에서 경로를 일딴 받아왔습니다. 저장에 필요한 경로
ci = (CropImage)findViewById(R.id.crop_view); // 커스텀 이미지뷰
findViewById(R.id.btn_ok).setOnClickListener(this);
findViewById(R.id.btn_cancle).setOnClickListener(this);
}
public void onClick(View v) {
Intent i = getIntent();
if(v.getId() == R.id.btn_ok) {
ci.save(); // 이미지 저장
setResult(RESULT_OK, i);
}
if(v.getId() == R.id.btn_cancle) {
setResult(RESULT_CANCELED, i);
}
System.gc();
finish();
}
public void onBackPressed() {
System.gc();
System.exit(0);
}
}
////////////////////////////////////////////////////////////////////////////////////
public class CropImage extends ImageView {
private static final String TAG = "Crop_Image";
float sx, ex , sy, ey;
static int DEP = 30; // Crop 경계선의 유효폭(선근처)
CropImageActivity cnxt;
Bitmap bitmap;
float mWidth;
float mHeight;
Paint pnt;
Bitmap hBmp; // 선 가운데의 세로선택 아이콘
Bitmap wBmp; // 가로
//private String outFilePath=Environment.getExternalStorageDirectory() + "/tmp.jpg";
String img; //<<<<여기서 전파일 경로를 받아와서 img 에 저장을해야합니다.
public CropImage(Context context, AttributeSet attrs) {
super(context, attrs);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mWidth = display.getWidth(); // 화면 크기 설정
mHeight = display.getHeight();
sx = mWidth/5; // 초기 Crop선의 위치 설정
ex = mWidth*4/5;
sy = mHeight/5;
ey = mHeight*4/5;
Log.e(TAG, img);
cnxt = (CropImageActivity)context;
// 비트맵 크기 조절(메모리 문제로 인하여 1/2 크기로)
BitmapFactory.Options resizeOpts = new Options();
resizeOpts.inSampleSize = 2;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(img), null, resizeOpts);
} catch(Exception e) {e.printStackTrace();}
bitmap = Bitmap.createScaledBitmap(bitmap, (int)mWidth, (int)mHeight, false);
Log.e(TAG, ""+bitmap.getHeight()*bitmap.getWidth());
hBmp = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.camera_crop_height);
wBmp = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.camera_crop_width);
// 페인트 설정
pnt = new Paint();
pnt.setColor(Color.MAGENTA);
pnt.setStrokeWidth(3);
}
public void onDraw(Canvas canvas) {
// 사각형 라인 그리기
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawLine(sx, sy, ex, sy, pnt);
canvas.drawLine(ex, sy, ex, ey, pnt);
canvas.drawLine(sx, sy, sx, ey, pnt);
canvas.drawLine(sx, ey, ex, ey, pnt);
// 상하좌우 버튼들
canvas.drawBitmap(hBmp, (ex+sx)/2-26, sy-45, null); // 폭이 38이므로 그려줄 좌상단 위치 지정
canvas.drawBitmap(hBmp, (ex+sx)/2-26, ey-45, null);
canvas.drawBitmap(wBmp, sx-45, (ey+sy)/2-26, null);
canvas.drawBitmap(wBmp, ex-45, (ey+sy)/2-26, null);
}
// 이벤트 처리, 현재의 그리기 모드에 따른 점의 위치를 조정
float dx=0, dy=0;
float oldx, oldy;
boolean bsx, bsy, bex, bey;
boolean bMove = false;
public boolean onTouchEvent(MotionEvent e) {
int x = (int)e.getX();
int y = (int)e.getY();
if(e.getAction() == MotionEvent.ACTION_DOWN) {
oldx = x;
oldy = y;
// 눌려진곳이 선 근처인가 확인
if( (x > sx-DEP ) && (x < sx+DEP ) )
bsx = true;
else
if( (x > ex-DEP ) && (x < ex+DEP) )
bex = true;
if( (y > sy-DEP ) && (y < sy+DEP ) )
bsy = true;
else
if( (y > ey-DEP ) && (y < ey+DEP ) )
bey = true;
// 어느 하나라도 선택이 되었다면 move에서 값 변경
if( (bsx || bex || bsy || bey) )
bMove = false;
else
if( ((x > sx+DEP) && (x < ex-DEP))
&& ( (y > sy+DEP) && (y < ey-DEP)))
bMove = true;
return true;
}
if(e.getAction() == MotionEvent.ACTION_MOVE) {
if(bsx) sx = x;
if(bex) ex = x;
if(bsy) sy = y;
if(bey) ey = y;
// 사각형의 시작 라인보다 끝라인이 크지않게 처리
if(ex<=sx+DEP){
ex=sx+DEP;
return true;
}
if(ey<=sy+DEP){
ey=sy+DEP;
return true;
}
// 움직인 거리 구해서 적용
if(bMove) {
dx = oldx - x;
dy = oldy - y;
sx -= dx;
ex -= dx;
sy -= dy;
ey -= dy;
// 화면밖으로 나가지않게 처리
if(sx <= 0) sx = 0;
if(ex >= mWidth) ex = mWidth-1;
if(sy <= 0) sy = 0;
if(ey >= mHeight) ey = mHeight-1;
}
invalidate(); // 움직일때 다시 그려줌
oldx = x;
oldy = y;
return true;
}
// ACTION_UP 이면 그리기 종료
if(e.getAction() == MotionEvent.ACTION_UP) {
bsx = bex = bsy = bey = bMove = false;
return true;
}
return false;
}
// 선택된 사각형의 이미지를 저장
public void save() {
Bitmap tmp = Bitmap.createBitmap(bitmap, (int)sx, (int)sy, (int)(ex-sx), (int)(ey-sy));
byte[] byteArray = bitmapToByteArray(tmp);
File file = new File(img);
Log.e("nicehee", file.getAbsolutePath());
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArray);
fos.flush();
fos.close();
} catch (Exception e) {
Toast.makeText(cnxt, "파일 저장 중 에러 발생 : " +
e.getMessage(), 0).show();
return;
}
}
// 이미지를 전송하기위한 테스트 코드
public byte[] bitmapToByteArray( Bitmap bitmap ) {
ByteArrayOutputStream stream = new ByteArrayOutputStream() ;
bitmap.compress( CompressFormat.JPEG, 100, stream) ;
byte[] byteArray = stream.toByteArray() ;
return byteArray ;
}
}
정말 간단한거 같은데 안되니 정말 미쳐버리겠습니다 살려주세요.




이미지뷰 받아온곳에서 바로 패스 넣어주시면 됩니다. 간단히 생각하세요. ㅎㅎ
...
ci = (CropImage)findViewById(R.id.crop_view); // 커스텀 이미지뷰
ci.img = imgpath;