패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.0.0

screenshot

Flutter 스크린샷 패키지(런타임). 어떤 위젯도 이미지로 캡처합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
61.7만
좋아요
1.6천
Pub 점수
140

패키지 설치

flutter pub add screenshot

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

스크린샷 패키지는 여러 플랫폼에서 런타임에 어떤 Flutter 위젯도 이미지로 캡처할 수 있도록 해줍니다. 앱 실행 중에 위젯의 스크린샷을 프로그래밍 방식으로 찍을 수 있어 디버깅, 테스트 또는 시각 콘텐츠 공유에 유용합니다. 이 패키지는 Android, iOS, 웹, macOS, Windows, Linux를 지원하여 매우 다양한 환경에서 사용 가능합니다. Flutter의 렌더링 파이프라인과 원활하게 통합되며, 위젯 트리에서 이미지를 생성하는 간단한 API를 제공합니다. 동적 이미지 생성이나 시각 피드백이 필요한 앱에 적합합니다.

사용 사례

  • UI 문제 디버깅
  • 공유 가능한 이미지 생성
  • 자동화 테스트
  • 시각 문서
  • 앱 튜토리얼
  • 미리보기 기능

주요 기능

  • 런타임 위젯 스크린샷 캡처
  • 크로스 플랫폼 지원
  • 간단한 API 통합
  • 고품질 이미지 출력
  • 모든 주요 플랫폼을 지원합니다
  • 외부 종속성 없음

적합한 대상

  • 동적 스크린샷이 필요한 개발자
  • 테스트 및 품질 보증 팀
  • 시각 공유 기능을 갖춘 앱
  • 교육용 또는 튜토리얼 앱
  • UI 프로토타이핑 도구
  • 복잡한 레이아웃 디버깅

고려 사항

  • 큰 위젯에서의 성능 영향
  • 고해상도 이미지의 메모리 사용량
  • 모바일 플랫폼에서 적절한 권한이 필요합니다
  • 실시간 비디오 캡처에 적합하지 않습니다
  • 정적 위젯 스냅샷으로 제한됨
  • 플랫폼별 구성이 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

screenshot

A simple package to capture widgets as Images. Now you can also capture the widgets that are not rendered on the screen!

This package wraps your widgets inside RenderRepaintBoundary

Source

screenshot

  Capture a widget:

screenshot

 Capture an invisible widget (a widget which is not part of the widget tree):

screenshot

Getting Started

This handy package can be used to capture any Widget including full screen screenshots & individual widgets like Text().

  1. Create Instance of Screenshot Controller
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Uint8List _imageFile;

  //Create an instance of ScreenshotController
  ScreenshotController screenshotController = ScreenshotController(); 

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  ...
}
  1. Wrap the widget that you want to capture inside Screenshot Widget. Assign the controller to screenshotController that you have created earlier
Screenshot(
    controller: screenshotController,
    child: Text("This text will be captured as image"),
),
  1. Take the screenshot by calling capture method. This will return a Uint8List
screenshotController.capture().then((Uint8List image) {
    //Capture Done
    setState(() {
        _imageFile = image;
    });
}).catchError((onError) {
    print(onError);
});

Capturing Widgets that are not in the widget tree

You can capture invisible widgets by calling captureFromWidget and passing a widget tree to the function

screenshotController
      .captureFromWidget(Container(
          padding: const EdgeInsets.all(30.0),
          decoration: BoxDecoration(
            border:
                Border.all(color: Colors.blueAccent, width: 5.0),
            color: Colors.redAccent,
          ),
          child: Text("This is an invisible widget")))
      .then((capturedImage) {
    // Handle captured image
  });


Capturing a List Widget

You can capture a long Invisible widgets by using captureFromLongWidget function.

var randomItemCount = Random().nextInt(100);

///
/// Step 1: Create Long widget using Column.
///

var myLongWidget = Builder(builder: (context) {
  return Container(
      padding: const EdgeInsets.all(30.0),
      decoration: BoxDecoration(
        border:
            Border.all(color: Colors.blueAccent, width: 5.0),
        color: Colors.redAccent,
      ),
      ///
      /// Note: Do not use Scrolling widget, instead place your children in Column. 
      ///  
      /// Do not use widgets like 'Expanded','Flexible',or 'Spacer'
      ///
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          for (int i = 0; i < randomItemCount; i++)
            Text("Tile Index $i"),
        ],
      ));
});

///
/// Step 2: 
///    Use `captureFromLongWidget` function for taking screenshot.
///
screenshotController
      .captureFromLongWidget(
          InheritedTheme.captureAll(
            context, 
            Material(
              child: myLongWidget,
            ),
          ),
          delay: Duration(milliseconds: 100),
          context: context,


          ///
          /// Additionally you can define constraint for your image.
          ///
          /// constraints: BoxConstraints(
          ///   maxHeight: 1000,
          ///   maxWidth: 1000,
          /// )
      )
      .then((capturedImage) {
    // Handle captured image
  });


Saving images to Specific Location

For this you can use captureAndSave method by passing directory location. By default, the captured image will be saved to Application Directory. Custom paths can be set using path parameter. Refer path_provider

Note

Method captureAndSave is not supported for web.

final directory = (await getApplicationDocumentsDirectory ()).path; //from path_provide package
String fileName = DateTime.now().microsecondsSinceEpoch;
path = '$directory';

screenshotController.captureAndSave(
    path //set path where screenshot will be saved
    fileName:fileName 
);

Saving images to Gallery

If you want to save captured image to Gallery, Please use https://github.com/hui-z/image_gallery_saver Example app uses the same to save screenshots to gallery.


Sharing Captured Images

await _screenshotController.capture(delay: const Duration(milliseconds: 10)).then((Uint8List image) async {
      if (image != null) {
        final directory = await getApplicationDocumentsDirectory();
        final imagePath = await File('${directory.path}/image.png').create();
        await imagePath.writeAsBytes(image);

        /// Share Plugin
        await Share.shareFiles([imagePath.path]);
      }
    });

Note:

Captured image may look pixelated. You can overcome this issue by setting value for pixelRatio

The pixelRatio describes the scale between the logical pixels and the size of the output image. It is independent of the window.devicePixelRatio for the device, so specifying 1.0 (the default) will give you a 1:1 mapping between logical pixels and the output pixels in the image.

double pixelRatio = MediaQuery.of(context).devicePixelRatio;

screenshotController.capture(
    pixelRatio: pixelRatio //1.5
)

Sometimes rastergraphics like images may not be captured by the plugin with default configurations. The issue is discussed here.

...screenshot is taken before the GPU thread is done rasterizing the frame 
so the screenshot of the previous frame is taken, which is wrong.

The solution is to add a small delay before capturing.

screenshotController.capture(delay: Duration(milliseconds: 10))

Known Issues

  • Platform Views are not supported. (Example: Google Maps, Camera etc)issue

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트