본문 바로가기
안드로이드 자바

[Android][Java] 사진에 투명한 밑줄긋기

by teamnova 2023. 4. 12.
728x90

안녕하세요. 색상 선택에 이어 투명한 밑줄을 사진에 그어보겠습니다.

색상 선택 라이브러리 사용법은 아래 글을 참고하세요.

https://stickode.tistory.com/739

 

책사진에 투명한 밑줄 긋기

 

목차

1. build.gradle

2. java

3. xml

 

 

 

1. 목차

라이브러리 그래들에 추가

    // 색상 선택
    implementation 'com.github.yukuku:ambilwarna:2.0.1'

매니페스트에 추가

<application
    android:usesCleartextTraffic="true"

 

만약 에러가 난다면

(DefaultLenientConfiguration ... app:debugRuntimeClasspath....)

그래들 설정을 다시 확인해보시기 바랍니다. 

maven을 추가해주었습니다.

++ 인터넷 등 권한도 확인해주세요

 

 

 

 

2. java


public class MainActivity extends AppCompatActivity {
    private final String TAG=this.getClass().getSimpleName();
    private Handler handler = new Handler();
    private String testUrl = "http://15.164.129.103/myNoteOfBook/cropped5639824668064416550.jpg";
    private Bitmap bitmapImg; // url to bitmap
    private MyPaintView myView;
    private LinearLayout painLayout;
    private int tColor = 0; // 직전선택색상


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // 도화지 그릴준비
        new Thread(() -> {
            bitmapImg = getBitmapFromURL(testUrl);


                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG,"bitmapImg:"+bitmapImg);
                        if (bitmapImg !=null) {
                            Log.e(TAG,"bitmapImg null이냐:"+bitmapImg);
                            myView = new MyPaintView(getApplicationContext(), bitmapImg);
                            painLayout = findViewById(R.id.paintLayout);
                            painLayout.addView(myView); // 도화지 (Layout이어야 함)
                        }
                    }
                });
        }).start();


        // 지우기
        ((Button)findViewById(R.id.btnClear)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { Log.e(TAG,"btnClear onClick / bitmapImg:"+bitmapImg);
                myView.mBitmap.eraseColor(Color.TRANSPARENT);

                Bitmap bImg = bitmapImg.copy(Bitmap.Config.ARGB_8888,true);
                bImg = Bitmap.createScaledBitmap(bImg, painLayout.getWidth(), painLayout.getHeight(), true);   // !! 위치 여기
                Log.e(TAG,"bitmapImg2:"+bitmapImg);
                Log.e(TAG,"bImg2:"+bImg);
                myView.mBitmap = bImg;
                myView.mCanvas.setBitmap(myView.mBitmap); // 객체 주소 주의!! 바로 bitmapImg넣으면 안 됨
                myView.invalidate(); // 무효화하다

            }
        });


        // 색상 선택
        ((ImageView)findViewById(R.id.choice)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { Log.e(TAG,"choice() onClick");
                openColorPicker();
            }
        });

    }

    private void openColorPicker() {
        AmbilWarnaDialog colorPicker = new AmbilWarnaDialog(this, tColor, new AmbilWarnaDialog.OnAmbilWarnaListener() {
            @Override
            public void onCancel(AmbilWarnaDialog dialog) {

            }

            @Override
            public void onOk(AmbilWarnaDialog dialog, int color) {
                tColor = color;
                Toast.makeText(getApplicationContext(),""+tColor,Toast.LENGTH_LONG).show();
                Log.e(TAG,"tColor:"+tColor);
                String hexColor = Integer.toHexString(color).substring(2);
                hexColor = "#4D"+hexColor;
                Log.e(TAG,"hexColor:"+hexColor); // 9자리


                myView.mPaint.setColor(Color.parseColor(hexColor));

            }
        });
        colorPicker.show();
    }

    // url -> bitmap
    // 주의!! stream사용 시 스레드 사용하기
    private Bitmap getBitmapFromURL(String src) {
        Log.e(TAG,"getBitmapFromURL src:"+src);

        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            Log.e(TAG,"myBitmap:"+myBitmap);

            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static class MyPaintView extends View {
        private final String TAG=this.getClass().getSimpleName();
        private Bitmap originalBitmap;
        private Bitmap mBitmap;
        private Canvas mCanvas;
        private Path mPath;
        private Paint mPaint;
        private LinearLayout linearLayout;

        public MyPaintView(Context context, Bitmap bitmap) {
            super(context);
            Log.e(TAG,"bitmap:"+bitmap);
            originalBitmap = bitmap; // url to bitmap 이미지
            mPath = new Path();
            mPaint = new Paint();
            mPaint.setColor(Color.parseColor("#4Dd55151"));
            mPaint.setAntiAlias(true);
            mPaint.setStrokeWidth(35);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeCap(Paint.Cap.BUTT);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh); Log.e(TAG,"onSizeChanged()"); Log.e(TAG,"w:"+w+"/h:"+h);
            Log.e(TAG,"originalBitmap:"+originalBitmap);


            mBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888,true);
            mBitmap = Bitmap.createScaledBitmap(mBitmap, w, h, true);   // !! 위치 여기
            mCanvas = new Canvas(mBitmap); // 도화지에 비트맵을 뿌려넣는다
        }

        @SuppressLint("DrawAllocation")
        @Override
        protected void onDraw(Canvas canvas) {
            Log.e(TAG,"onDraw()");
            Log.e(TAG,"width:"+ getWidth()+"/height:"+getHeight());
            canvas.drawBitmap(mBitmap, 0, 0, null); //지금까지 그려진 내용
            canvas.drawPath(mPath, mPaint); //현재 그리고 있는 내용
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            Log.e(TAG,"onTouchEvent()");
            int x = (int)event.getX();
            int y = (int)event.getY();

            Log.e(TAG,"x:"+x+"y:"+y);

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.e(TAG,"ACTION_DOWN");
                    mPath.reset();
                    mPath.moveTo(x, y);
                    break;
                case MotionEvent.ACTION_MOVE:
                    Log.e(TAG,"ACTION_MOVE");
                    mPath.lineTo(x, y);
                    break;
                case MotionEvent.ACTION_UP:
                    Log.e(TAG,"ACTION_UP");
                    mPath.lineTo(x, y);
                    mCanvas.drawPath(mPath, mPaint); //mBitmap 에 기록
                    mPath.reset();
                    break;
            }
            this.invalidate();
            return true;
        }
    }


}

** 투명도 조절하는 곳

hexColor = "#4D"+hexColor;

 

 

 

3. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical">

    <LinearLayout
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <ImageView
            android:src="@drawable/ic_paint"
            android:id="@+id/choice"
            android:layout_width="50dp"
            android:layout_height="40dp"
            />
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            />
        <Button
            android:layout_gravity="center"
            android:id="@+id/btnClear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="CLEAR"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="70dp"
        android:id="@+id/paintLayout"
        android:layout_width="match_parent"
        android:layout_height="230dp"
        android:background="#735252"
        android:orientation="vertical" />

    <Button
        android:layout_gravity="bottom"
        android:layout_marginTop="70dp"
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="확인" />
</LinearLayout>

이미지뷰의 소스는 개인이 넣어주세요.