Search code examples
cssangularionic-frameworkcss-grid

Split Image into parts ionic


I want to divide the image into multiple parts dynamically based on dimensions in ionic 5.

let's say

  • 3 piece
  • 8 piece
  • any number

I tried css tricks to make white color line on image but that hides the image portion behind.

I read this two blocks but helped me

split base64 image into parts

Split image into parts

I want to show preview of selection.

reference image Please help


Solution

  • First of all, you have to generate a component. I named it img-tile-style. then you put this codes in .html .css and .ts files.

    HTML:

    <div class="image-holder">
      <img [src]="imgSrc">
      <div class="grid"></div>
    </div>
    

    CSS: (change the img -> width & height and the .grid -> border color for customization)

    .image-holder {
      width: fit-content;
      height: fit-content;
      position: relative;
    }
    
    .image-holder img {
      width: 300px;
      height: 400px;
    }
    
    .image-holder .grid {
      display: flex;
      flex-direction: column;
      position: absolute;
      top: 0;
      right: 0;
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      border: 1px gray solid;
    }
    

    TypeScript: (change the border color for customization)

    export class ImgTileStyleComponent implements OnInit {
    
      @Input() imgSrc: string;
      @Input() row: number;
      @Input() col: number;
    
      constructor() {}
    
      ngOnInit(): void {
        console.log(this.imgSrc, this.row, this.col);
    
        console.log('here');
        const grid = document.getElementsByClassName('grid')[0];
        console.log(grid);
        const row = '<div class="row" style="display: flex; flex-direction: row; flex-grow: 1;"></div>';
        const cell = '<div class="cell" style="flex-grow: 1; box-sizing: border-box; border: 1px gray solid;"></div>';
        for (let i = 0; i < this.row; i++) {
          grid.insertAdjacentHTML('beforeend', row);
        }
        for (let i = 0; i < this.row; i++) {
          const el = document.getElementsByClassName('row')[i];
          for (let j = 0; j < this.col; j++) {
            el.insertAdjacentHTML('beforeend', cell);
          }
        }
      }
    
    }
    

    then in your project simply you use the tag: <app-img-tile-style></app-img-tile-style>

    the attributes you have to set are:

    imgSrc imgSrc="./assets/images/defaultCompanyPic.png"

    row -> row="4"

    col -> col="3"

    a complete example here:

    <app-img-tile-style imgSrc="./assets/images/defaultCompanyPic.png" row="4" col="3"></app-img-tile-style>
    

    I put this component on a repository on Github. Link: img-tile-style.