支持图像裁剪功能
| Files | Last commit | Last update |
|---|---|---|
| 8 months ago | ||
| 6 months ago | ||
| 8 months ago | ||
| 5 months ago | ||
| 8 months ago | ||
| 8 months ago | ||
| 8 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 8 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 8 months ago | ||
| 8 months ago | ||
| 8 months ago | ||
| 8 months ago |
ohos_SimpleCropView
This project is developed based on SimpleCropView.
Introduction
ohos_SimpleCropView is a lightweight and highly customizable open-source image cropping library. It is designed to simplify complex image cropping workflows by providing an intuitive cropping interface, gesture operations (zoom / pan / rotate), and extensive customization options. It is suitable for implementing image cropping features across multiple platforms while ensuring consistent functionality and user experience.
Integration
Prerequisites
- DevEco Studio 6.0.0 Release or later
- OpenHarmony SDK API version 12 or later
How to Integrate
-
Install the package
ohpm install @ohos/simplecropview -
Usage example
// 1. Create a load request
const loadRequest = new LoadRequest('resource://...')
.setInitialFrameScale(0.8)
.setUseThumbnail(true)
// 2. Create a crop request
const cropRequest = new CropRequest()
.setOutputWidth(800)
.setOutputMaxWidth(1920)
// 3. Create a controller (for rotation/custom ratio)
const cropImageController = new CropImageController()
// 4. Create the component
@Entry
@Component
struct CropPage {
loadRequest: LoadRequest = loadRequest
cropRequest: CropRequest = cropRequest
cropImageController: CropImageController = cropImageController
build() {
Column() {
CropImageView({
cropImageController: this.cropImageController,
loadRequest: this.loadRequest,
cropRequest: this.cropRequest,
cropMode: CropMode.SQUARE,
guideShowMode: ShowMode.SHOW_ALWAYS
})
}
}
}
// 5. Load the image
loadRequest.execute().then(success => {
console.log('Image loaded successfully')
})
// 6. Perform cropping
cropRequest.execute().then(pixelMap => {
if (pixelMap) {
// 7. Save the image
const saveRequest = new SaveRequest('file://...', pixelMap)
.setCompressFormat(CompressFormat.JPEG)
.setCompressQuality(90)
saveRequest.execute().then(path => {
console.log('Saved successfully:', path)
})
}
})
Directory Structure
library/
│
├── src/ # Source code directory
│ ├── main/ # Main code directory
│ │ ├── ets/ # ArkTS source code
│ │ │ ├── bean/ # Data model layer
│ │ │ │ ├── CompressFormat.ets # Compression format enum
│ │ │ │ ├── CropMode.ets # Crop mode enum
│ │ │ │ ├── GuideLine.ets # Guideline data model
│ │ │ │ ├── HandlePointType.ets # Handle point type enum
│ │ │ │ ├── Point.ets # Point data model
│ │ │ │ ├── Region.ets # Region data model
│ │ │ │ ├── RotateDegrees.ets # Rotation degree enum
│ │ │ │ └── ShowMode.ets # Display mode enum
│ │ │ │
│ │ │ ├── callback/ # Callback interface layer
│ │ │ │ └── Callback.ets # Callback interface definitions
│ │ │ │
│ │ │ ├── util/ # Utility layer
│ │ │ │ └── Utils.ets # Utility function collection
│ │ │ │
│ │ │ ├── CropImageView.ets # Crop view component (core component)
│ │ │ ├── CropImageController.ets # Image crop component controller
│ │ │ ├── CropRequest.ets # Image crop request class
│ │ │ ├── LoadRequest.ets # Image load request class
│ │ │ └── SaveRequest.ets # Image save request class
│ │ │
│ │ ├── module.json5 # Module configuration file
│ │ │
│ │ └── resources/ # Resource directory
│ │ └── base/
│ │ └── element/
│ │ ├── float.json # Float resources
│ │ └── string.json # String resources
│
├── BuildProfile.ets # Build configuration file
├── build-profile.json5 # Build configuration file
├── consumer-rules.txt # Consumer rules file
├── hvigorfile.ts # Hvigor build script
├── index.ets # Library entry file
├── obfuscation-rules.txt # Code obfuscation rules
└── oh-package.json5 # HarOS package configuration file
API Reference
CropImageView
CropImageView is an important component used to display and crop images.
| Property Name | Type | Required | Description |
|---|---|---|---|
| cropImageController | CropImageController | Yes | Crop view controller used to rotate the image and set a custom ratio |
| cropMode | CropMode | Yes | Crop mode property that defines how the image is cropped |
| mBackgroundColor | ResourceColor | No | Sets the background color |
| overlayColor | string\number | No | Overlay color |
| frameColor | string\number | No | Frame color |
| handleColor | string\number | No | Handle color |
| guideColor | string\number | No | Guideline color |
| guideShowMode | ShowMode | No | Guideline display mode |
| handleShowMode | ShowMode | No | Handle display mode |
| handleSize | number | No | Handle size |
| touchPadding | number | No | Handle touch padding |
| minFrameSize | number | No | Minimum crop frame size |
| frameStrokeWeight | number | No | Frame stroke width |
| guideStrokeWeight | number | No | Guideline stroke width |
| cropEnabled | boolean | No | Whether cropping is enabled |
| animationEnabled | boolean | No | Whether animation is enabled |
| animationDuration | number | No | Animation duration (milliseconds) |
| handleShadowEnabled | boolean | No | Whether handle shadow is enabled |
| canvasPadding | Padding | Length | LocalizedPadding | No | Canvas padding |
| loadRequest | LoadRequest | Yes | Load request |
| cropRequest | CropRequest | Yes | Crop request |
| isDebug | boolean | No | Whether debug mode is enabled |
| initialFrameScale | number | No | Initial crop frame scale, range: 0.01 to 1 (overridden if LoadRequest.setInitialFrameScale(value: number) is also called) |
CropImageController
CropImageController is used to control CropImageView for rotation and custom ratio operations.
| Method | Parameters | Description |
|---|---|---|
| rotateImage(degrees: RotateDegrees) | degrees: rotation degree enum value | Rotates the current image |
| setCustomRatio(ratioX: number, ratioY: number) | ratioX / ratioY: custom aspect ratio | Sets a custom crop ratio (used with CropMode.CUSTOM) |
LoadRequest
LoadRequest is an image load request used to load image resources.
| Method | Parameters | Description |
|---|---|---|
| constructor(sourceUri: string | number | image.PixelMap) | sourceUri: image resource URI | Creates an image load request |
| setInitialFrameScale(value: number): LoadRequest | value: scale ratio | Sets the initial crop frame scale |
| setInitialFrameRect(value: Region | undefined): LoadRequest | value: initial crop frame region | Sets the initial crop frame region |
| setUseThumbnail(value: boolean): LoadRequest | value: whether to use a thumbnail | Sets whether to use a thumbnail |
| setSourceUri(value: string | number| image.PixelMap): LoadRequest | value: image resource URI | Sets the image resource to load |
| executeCallback(callBack: LoadCallback) | callBack: load result callback | Executes the load operation (callback style) |
| execute(): Promise | Executes the load operation (Promise style) |
CropRequest
CropRequest is an image crop request used to crop images.
| Method | Parameters | Description |
|---|---|---|
| constructor(isOriginalImageCrop: boolean = false) | isOriginalImageCrop: whether to crop the original image | Creates a crop request |
| setOutputWidth(outputWidth:number) | outputWidth: output crop width in px | Sets the output crop width. When set, the output height becomes 0 |
| setOutputHeight(outputHeight:number) | outputHeight: output crop height in px | Sets the output crop height. When set, the output width becomes 0 |
| setOutputMaxWidth(outputMaxWidth:number) | outputMaxWidth: maximum output crop width in px | Sets the maximum output width. When both maximum width and height are set, the cropped image is scaled proportionally to fit within them |
| setOutputMaxHeight(outputMaxHeight:number) | outputMaxHeight: maximum output crop height in px | Sets the maximum output height. When both maximum width and height are set, the cropped image is scaled proportionally to fit within them |
| setIsOriginalImageCrop(value: boolean): CropRequest | value: whether to crop the original image | Sets whether to crop the original image. true: crop the original image; false: crop the image already loaded on the page |
| executeCallback(cropCallback: CropCallback) | cropCallback: crop result callback | Executes the crop operation (callback style) |
| execute(): Promise<image.PixelMap | null> | Executes the crop operation (Promise style) |
SaveRequest
SaveRequest is an image save request used to save images.
| Method | Parameters | Description |
|---|---|---|
| constructor(savaUri: string, pixelMap: image.PixelMap) | savaUri: save path; pixelMap: image | Creates a request to save the cropped image |
| setCompressFormat(format: CompressFormat): SaveRequest | format: compression format enum value | Sets the compression format. Supports CompressFormat.JPEG, CompressFormat.WEBP, CompressFormat.PNG, CompressFormat.HEIC, and CompressFormat.HEIF (HEIC/HEIF require ROM image support; HEIC is not supported before SDK API14) |
| setCompressQuality(quality: number): SaveRequest | quality: image quality | Sets the compression quality, range: [0, 100]. 0 is the lowest quality and 100 is the highest. Higher quality results in larger file size. (PNG is lossless and does not support image quality settings) |
| execute(): Promise<string| null> | Executes the save operation (Promise style) | |
| executeCallback(callBack: SaveCallback) | callBack: save callback | Executes the save operation (callback style) |
CropCallback
| Method Name | Parameters | Return Type | Description |
|---|---|---|---|
| onSuccess | pixelMap: image.PixelMap | void | Crop success callback |
| onError | error: Error | void | Error callback |
LoadCallback
| Method Name | Parameters | Return Type | Description |
|---|---|---|---|
| onSuccess | None | void | Load success callback |
| onError | error: Error | void | Error callback |
SaveCallback
| Method Name | Parameters | Return Type | Description |
|---|---|---|---|
| onSuccess | uri: string | void | Save success callback |
| onError | error: Error | void | Error callback |
CropMode
CropMode is an enum type for crop modes, corresponding to different crop frame ratios.
| key | Description |
|---|---|
| FIT_IMAGE | Fit image ratio |
| RATIO_4_3 | 4:3 ratio |
| RATIO_3_4 | 3:4 ratio |
| SQUARE | Square |
| RATIO_16_9 | 16:9 ratio |
| RATIO_9_16 | 9:16 ratio |
| FREE | Free crop |
| CUSTOM | Custom ratio |
| CIRCLE | Circle crop |
| CIRCLE_SQUARE | Display as circle, save as square |
ShowMode
ShowMode is an enum for the display modes of crop frame handles and guidelines.
| key | Description |
|---|---|
| SHOW_ALWAYS | Always show |
| SHOW_ON_TOUCH | Show on touch |
| NOT_SHOW | Do not show |
RotateDegrees
RotateDegrees is an enum for rotation angles.
| key | Description |
|---|---|
| ROTATE_90D | Rotate 90° clockwise |
| ROTATE_180D | Rotate 180° clockwise |
| ROTATE_270D | Rotate 270° clockwise |
| ROTATE_M90D | Rotate 90° counterclockwise (-90°) |
| ROTATE_M180D | Rotate 180° counterclockwise (-180°) |
| ROTATE_M270D | Rotate 270° counterclockwise (-270°) |
CompressFormat
CompressFormat is an enum for image compression formats when saving images.
| key | Description |
|---|---|
| JPEG | JPEG format (image/jpeg) |
| PNG | PNG format (image/png) |
| WEBP | WEBP format (image/webp) |
| HEIC | HEIC format (image/heic, requires ROM image support; not supported before SDK API14) |
| HEIF | HEIF format (image/heif, requires ROM image support) |
Region
Region is a custom type representing a rectangular region.
| Property Name | Description |
|---|---|
| x | X coordinate of the rectangle's top-left corner (vp unit) |
| y | Y coordinate of the rectangle's top-left corner (vp unit) |
| width | Rectangle width (vp unit) |
| height | Rectangle height (vp unit) |
Constraints and Limitations
Verified on the following version:
- DevEco Studio version: 6.0.2.640, SDK: API12 (5.0.0(12))
About Obfuscation
- For code obfuscation, see Code Obfuscation Overview
- If you want the
ohos_SimpleCropViewlibrary to remain unobfuscated during code obfuscation, add the following exclusion rule toobfuscation-rules.txt:
-keep
./oh_modules/@ohos/simplecropview
Open Source License
This project is licensed under MIT. Feel free to use and contribute to this open-source project.
Contributing
If you encounter any issues while using the library, feel free to submit an Issue. Pull requests are also very welcome: PR.