How to Capture a Specific Android LinearLayout as an Image
Capture one Android LinearLayout as a bitmap with View.draw, or use PixelCopy when you need the actual rendered window pixels.
To capture an already laid-out LinearLayout, create a Bitmap, wrap it in a Canvas, and call linearLayout.draw(canvas). This renders the layout and its child views into the bitmap. Android recommends this Canvas-backed approach for software-rendered snapshots of an individual View or a small part of a View hierarchy. See the Android View API reference.
1. Capture a LinearLayout with Java
Run the capture after the layout has been measured and laid out, such as from a click listener, posted callback, or later lifecycle event.
LinearLayout linearLayout = findViewById(R.id.receipt_layout);
int width = linearLayout.getWidth();
int height = linearLayout.getHeight();
if (width <= 0 || height <= 0) {
// The view has not been measured and laid out yet.
return;
}
Bitmap bitmap = Bitmap.createBitmap(
width,
height,
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(bitmap);
linearLayout.draw(canvas);
// Use bitmap: save it, share it, or display it in an ImageView.
getWidth() and getHeight() are pixel dimensions of the view's current on-screen size. The result includes the LinearLayout's descendants that participate in normal View drawing.
2. Kotlin version
val linearLayout = findViewById<LinearLayout>(R.id.receipt_layout)
val width = linearLayout.width
val height = linearLayout.height
if (width <= 0 || height <= 0) {
return // Wait until measurement and layout are complete.
}
val bitmap = Bitmap.createBitmap(
width,
height,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
linearLayout.draw(canvas)
// Use bitmap: save it, share it, or display it.
3. Make sure capture happens after layout
A newly inflated view can have zero dimensions. Capture after setContentView and layout have completed, or post the work to the view.
linearLayout.post(() -> {
int width = linearLayout.getWidth();
int height = linearLayout.getHeight();
if (width > 0 && height > 0) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
linearLayout.draw(new Canvas(bitmap));
}
});
If the layout is not attached or has not received constraints, the capture has no reliable size. This guide does not assume a particular off-screen measurement recipe; choose measurements that match your app's layout requirements.
4. Save the bitmap as PNG or JPEG
Use PNG when you need lossless output or transparency. Use JPEG for smaller photographic output; JPEG does not preserve transparency.
File output = new File(getCacheDir(), "linear-layout.png");
try (FileOutputStream stream = new FileOutputStream(output)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
} catch (IOException e) {
Log.e("Capture", "Could not save bitmap", e);
}
For a user-visible export, use Android's storage and sharing APIs appropriate to your target SDK. A cache file is suitable for temporary sharing but may be deleted by the system.
5. Choosing the right capture method
| Requirement | Use | Limitation |
|---|---|---|
| One ordinary LinearLayout and its children | Bitmap + Canvas + View.draw |
Software rendering may differ from hardware rendering. |
| Actual pixels composited by a Window or Surface | PixelCopy |
Asynchronous; the source must have a rendered buffer. |
| Only the LinearLayout area from a Window | PixelCopy with a source rectangle |
You must calculate the view's window coordinates. |
| Legacy drawing cache reuse | Avoid for new code | Drawing-cache APIs were deprecated in API 28. |
Android's View documentation recommends Canvas snapshots for small View hierarchies and notes that software rendering can differ from hardware rendering, including hardware-only effects such as real-time shadows and outline clipping.
6. When PixelCopy is the better choice
Use PixelCopy when the requirement is to copy the pixels actually rendered by a Window, Surface, or SurfaceView. It copies the most recently queued source buffer into a destination bitmap and reports completion asynchronously. See the PixelCopy API reference.
Capture a Window region corresponding to the LinearLayout
A Window request is not automatically cropped to the target View. Find the view's location in window coordinates, create a matching source rectangle, and pass it to the request.
LinearLayout target = findViewById(R.id.receipt_layout);
Window window = getWindow();
int[] location = new int[2];
target.getLocationInWindow(location);
Rect sourceRect = new Rect(
location[0],
location[1],
location[0] + target.getWidth(),
location[1] + target.getHeight()
);
if (sourceRect.width() <= 0 || sourceRect.height() <= 0) {
return;
}
Bitmap destination = Bitmap.createBitmap(
sourceRect.width(),
sourceRect.height(),
Bitmap.Config.ARGB_8888
);
PixelCopy.request(
window,
sourceRect,
destination,
result -> {
if (result == PixelCopy.SUCCESS) {
// destination contains the cropped Window pixels.
} else {
Log.e("PixelCopy", "Copy failed: " + result);
}
},
new Handler(Looper.getMainLooper())
);
The source rectangle is clamped to the surface bounds, and source pixels are scaled to the destination dimensions. Matching the destination dimensions to the crop avoids unintended rescaling.
PixelCopy prerequisites and errors
- The Window needs a non-null DecorView and an acquired backing surface.
- A real draw should occur before requesting the copy. Android documents waiting for a draw, for example with an
OnDrawListener. - Handle completion results such as invalid source, no source data, invalid destination, and timeout.
- Because the operation is asynchronous, do not read or export the bitmap until the callback reports success.
7. Why not use the drawing cache?
Do not lead new implementations with setDrawingCacheEnabled(true), buildDrawingCache(), or getDrawingCache(). Android deprecated these APIs in API 28. The documented replacement for a software snapshot is a Bitmap- or Picture-backed Canvas with View.draw(Canvas); PixelCopy is recommended for rendered UI screenshots and testing scenarios.
8. Edge cases
Nested and scrollable content
draw(canvas) renders the View at its current measured size. A child that is clipped or outside the current bounds is not automatically expanded into a full document image. For a scroll container, decide whether you need the visible viewport or a separately measured full-content layout.
Hardware-backed effects
Canvas software snapshots can differ from the hardware-composited screen. Real-time shadows, outline clipping, and content rendered by a separate surface may not appear as expected. Choose PixelCopy when those pixels matter.
Transparent backgrounds
ARGB_8888 preserves alpha in the bitmap. A view or parent that paints an opaque background will still produce opaque pixels.
Large layouts
Bitmap memory grows with width × height × bytes per pixel. A large ARGB_8888 bitmap uses roughly four bytes per pixel, so avoid creating several full-size copies at once. Recycle or release references promptly when the bitmap is no longer needed.
9. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Bitmap is empty or has width 0 | Capture ran before measurement/layout. | Call from a later lifecycle point or use post; verify dimensions first. |
| Only part of the content appears | The view's measured bounds or clipping limit the draw. | Capture the intended viewport, or measure a separate full-content layout. |
| Shadows or clipping differ from the screen | Software Canvas rendering differs from hardware composition. | Use PixelCopy for Window or Surface pixels. |
| PixelCopy reports no source data | The Window or Surface has not produced a buffer yet. | Wait for a draw and retry after the backing surface is ready. |
| PixelCopy crop is offset | Coordinates were taken in screen or view space instead of Window space. | Use getLocationInWindow and a rectangle matching the view bounds. |
| OutOfMemoryError | Bitmap is too large or several copies are retained. | Reduce dimensions, avoid duplicate bitmaps, and release references promptly. |
| Legacy cache code fails on newer Android | Drawing-cache APIs are deprecated. | Replace it with Canvas + draw or PixelCopy. |
10. Checklist
- Confirm the LinearLayout has been measured and laid out.
- Read its current width and height in pixels.
- Create an
ARGB_8888bitmap with those dimensions. - Draw the view into a Canvas backed by that bitmap.
- Use PixelCopy instead when you need Window, Surface, or SurfaceView pixels.
- For a Window crop, calculate bounds with
getLocationInWindow. - Handle asynchronous PixelCopy errors.
- Keep bitmap dimensions and retained references under control.
Or skip the browser setup
If your goal is a web screenshot rather than an in-app Android View bitmap, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. Cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, timeouts, failed loads, and cache hits are never billed. Its MCP server lets AI agents call take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 shots. See the ScreenshotNeo API documentation.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Create a free ScreenshotNeo account and start with 1,000 screenshots a month without adding a card.
FAQ
Can I capture a LinearLayout before it is visible?
The documented approach depends on valid measured dimensions. If the view has not been laid out, its width or height may be zero; arrange capture after measurement and layout.
Does draw capture a SurfaceView inside the layout?
Use PixelCopy when content is rendered through a separate Surface or when you need the composited Window pixels.
Should I use PNG or JPEG?
Choose PNG for lossless output and alpha. Choose JPEG when lossy compression and no transparency are acceptable.
Is PixelCopy synchronous?
No. PixelCopy completes asynchronously through its callback, and the result code must be checked.


