[flutter] photo_view 패키지로 이미지 컨투어(윤곽선) 추가하기

이번 글에서는 Flutter의 photo_view 패키지를 사용하여 이미지에 컨투어(윤곽선)를 추가하는 방법에 대해 알아보겠습니다.

photo_view 패키지란?

photo_view는 Flutter에서 이미지를 확대, 축소 및 드래그 이동할 수 있는 위젯입니다. 또한, 여러 가지 기능과 옵션을 제공하여 이미지를 조작하는 모든 작업을 쉽게 할 수 있도록 도와줍니다.

설치하기

먼저, pubspec.yaml 파일에 photo_view 패키지를 추가해야 합니다. 아래와 같이 dependencies 항목에 추가하고, 패키지를 가져옵니다.

dependencies:
  flutter:
    sdk: flutter
  photo_view: ^0.11.1

그리고 터미널에서 flutter pub get 명령어를 실행하여 패키지를 설치합니다.

사용하기

photo_view를 사용하기 위해서는 PhotoView 위젯을 사용해야 합니다. 아래는 기본적인 사용법입니다.

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';

class MyPhotoView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Photo View'),
      ),
      body: Container(
        child: PhotoView(
          imageProvider: AssetImage('assets/images/my_image.jpg'),
        ),
      ),
    );
  }
}

위 코드에서 imageProvider 속성을 사용하여 이미지를 제공할 수 있습니다. 이미지는 AssetImage, NetworkImage, FileImage 중 하나로 설정할 수 있습니다.

이미지 컨투어 추가하기

이미지에 컨투어를 추가하기 위해서는 photo_view 패키지의 CustomPaint와 CustomPainter를 사용해야 합니다. 아래는 예시 코드입니다.

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';

class MyCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // 이미지 위에 원하는 윤곽선을 그립니다.
    Paint paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 5;

    // 윤곽선을 그리는 로직을 작성합니다. 예시로 원을 그립니다.
    double centerX = size.width / 2;
    double centerY = size.height / 2;
    double radius = 100;

    canvas.drawCircle(Offset(centerX, centerY), radius, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

class MyPhotoView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Photo View'),
      ),
      body: Container(
        child: PhotoView.customChild(
          child: Container(
            child: CustomPaint(
              painter: MyCustomPainter(),
              child: Image.asset('assets/images/my_image.jpg'),
            ),
          ),
          childSize: Size(300, 300),
        ),
      ),
    );
  }
}

위 코드에서 MyCustomPainter 클래스는 CustomPainter를 상속하여 커스텀 페인팅 로직을 작성합니다. paint() 메서드에서는 원하는 윤곽선을 그리도록 로직을 작성하였습니다.

이후, MyPhotoView 위젯에서 PhotoView.customChild를 사용하여 이미지와 컨투어를 함께 보여줍니다. 컨투어에 사용할 CustomPaint 위젯 안에는 MyCustomPainter를 지정하고, 이미지는 Image.asset으로 가져옵니다.

결론

이번에는 Flutter의 photo_view 패키지를 사용하여 이미지에 컨투어를 추가하는 방법에 대해 알아보았습니다. photo_view 패키지를 사용하면 이미지를 손쉽게 확대, 축소하고 컨투어를 추가할 수 있습니다. 편리한 기능과 다양한 옵션을 활용하여 원하는 모양의 컨투어를 만들어보세요.