DEV Community

HarmonyOS
HarmonyOS

Posted on

Dynamically set the corner radius of an Image.

Read the original article:Dynamically set the corner radius of an Image.

Problem Description

The issue is that when using the Slider component to dynamically control the corner radius (border radius) of an Image component while sliding, the corner radius does not change.

Background Knowledge

Clip: Used for clipping and masking components.

borderRadius: Sets the border's corner radius. The radius size is limited by the component's dimensions, with the maximum value being half of the component's width or height.

Slider: A sliding bar component, typically used for quickly adjusting settings values in scenarios like volume control or brightness adjustment.

$$ Syntax: Built-in component two-way synchronization.

Solution

Regarding the issue where the corner radius does not change when sliding the Slider, pay attention to the following points:

  1. To synchronize the change in the Image component's corner radius with the value of the Slider component, you need to two-way bind the .borderRadius() property value and the Slider component's value.
  2. After successfully implementing the corner radius change effect, if you need the image content to conform to the new radius, you need to add the .clip(true) attribute to the Image component.

Below is the complete example code:

@Entry
@Component
struct Index {
  // State variable for the corner radius
  @State radius: number = 0

  build() {
    Column() {

      Image($r('app.media.background'))
        .width(100)
        .borderRadius(this.radius)
        .clip(true) // Clip the image content that exceeds the Image component boundaries

      Column() {
        Text(this.radius + 'PX')
          .fontColor('#007AFF')

        Slider({
          min: 0,
          max: 60,
          style: SliderStyle.OutSet,
          value: $$this.radius // Two-way binding
        })
          .blockSize({ width: 20, height: 20 })
          .trackColor('#E5E5EA')
          .selectedColor('#007AFF')
          .trackThickness(6)
          .width('100%')
          .margin({
            top: 7,
            bottom: 13
          })
      }
    }
    .padding(50)
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Verification Result

s.gif

Written by Muhammet Ali Ilgaz

Top comments (0)